0
votes

I'm new to image processing and development. I need to take the inside triangle pixels of the image. In order to do it I used the following code. Unfortunately I obtain unwanted black pixels. get rid of that problem i tried to remove background[0] pixels by giving alfa value.(tranparent background) But it gives following Error. Any help is appreciated.

My code:

Mat img = cv::imread("/home/fabio/code/lena.jpg", cv::IMREAD_GRAYSCALE);

Mat alpha(img.size(), CV_8UC1, Scalar(0));

//triangle definition (example points)
vector<Point> points;
points.push_back(Point(200, 70));
points.push_back(Point(60, 150));
points.push_back(Point(500, 500));

//apply triangle to mask
fillConvexPoly(alpha, points, Scalar(255));

cv::Mat finalImage = cv::Mat::zeros(img.size(), img.type());

img.copyTo(finalImage, alpha);

imshow("image", finalImage);

Mat dst;

Mat rgb[1];
split(finalImage, rgb);
Mat rgba[2] = { finalImage, alpha };
merge(rgba, 2, dst);

imshow("dst", dst); 

Error: OpenCV Error: Bad number of channels (Source image must have 1, 3 or 4 channels) in cvConvertImage, file C:\builds\2_4_PackSlave-win64-vc12-shared\opencv\modules\highgui\src\utils.cpp, line 611

What i need to do

1
your input image is loaded as grayscale, that's why it isn't RGB but only a single channels. Adding the alpha channel will reach a 2 channel image which isn't displayable. Please keep in mind that openCV won't handle the alpha channel correctly during displaying with imshow, so better save as .png to test the alpha channel feature.Micka

1 Answers

1
votes

use this instead of your last block:

std::vector<cv::Mat> channels; 
cv::split(finalImage,m channels);
if(channels.size() == 0)
{
    std::cout << "unexpected error" << std::endl;
    return 1;
}
// fill up to reach 3 channels
while(channels,size() < 3)
{
    channels.push_back(channels[0]);
}
// add alpha channel
channels.push_back(alpha); 
cv::merge(channels, dst);

I didn't test it but this should be what you want?