简体   繁体   English

复制图像将黑色像素更改为白色像素

[英]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复制到img2img2=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 . 使用copyTocvtColor 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.

相关问题 将图像中的所有白色像素转换为黑色像素 - Convert all white pixels in the image into black pixels PIL 图像开孔将白色像素变成黑色像素 - PIL Image opening turns white pixels into black pixels opencv python复制掩模区域(黑色或白色像素)到BGR图像区域上 - opencv python copy mask region (black or white pixels) onto a BGR image region 如何循环所有图像像素并判断它们是黑色还是白色 - How to loop all image pixels and tell whether they are black or white Python:灰度图像:使所有内容变为白色,黑色像素除外 - Python: Greyscale image: Make everything white, except for black pixels 数不了。 使用OpenCV的图像中的黑色到白色像素 - Counting the no. of black to white pixels in the image using OpenCV 如何使用python计算二进制图像中的黑白像素 - how to count black and white pixels in binary image using python 从图像中复制黑色像素并粘贴到具有偏移的同一图像中 - Copy black pixels from image and paste in same image with offset 遍历所有像素以检查哪些像素为白色,哪些像素为黑色 - Iterate over all pixels to check which pixels are white and which are black 循环浏览2张图像的所有像素,并将黑色像素替换为白色 - Loop through all pixels of 2 images and replace the black pixels with white
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM