[英]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. 我正在阅读图片(
img1=cv2.imread('picture.jpg')
),其中只有一个对象,背景为黑色。
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. 我想像这样将
img1
复制到img2
: img2=img1.copy()
但我想在img2
中将img1
所有黑色像素(背景)设置为白色。 How can I reach this goal ? 我怎样才能达到这个目标?
This should work: (In C++, see comments below) 这应该工作:( 在C ++中,请参阅下面的评论)
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 . 使用copyTo和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. 编辑:您还可以使用inRange创建蒙版。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.