简体   繁体   中英

Copy image changing black pixels into white pixels

I am reading pictures ( img1=cv2.imread('picture.jpg') ) on which there is only one object, and the background is black.

Note that the object has no black pixels.

I want to copy img1 to img2 like this: img2=img1.copy() But I want in img2 to have all the black pixels (backgroun) of img1 set to white. How can I reach this goal ?

This should work: (In C++, see comments below)

const cv::Mat img1=cv::imread('picture.jpg')

///Create a grayscale mask -> only pixel !=0 in the mask will be copied
cv::Mat mask(img1.size(),CV_8U); ///cvtColor requires output image to be already allocated
cv::cvtColor(img1, mask, CV_BGR2GRAY);

///Initialize output image to white
cv::Mat img2(img1.size(),CV_8UC3);
img2.setTo(cv::Scalar(255,255,255) );

///Copy pixels from the original image to the destination image, only where mask pixels != 0
img1.copyTo(img2,mask);

Using copyTo and cvtColor . The only problem is if within the input image you have pixels at zero out of the background. In that case you might prefer a floodfill approach, but probably is an overkill for your problem.

Edit: You can also use inRange to create your mask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM