我正在读取只有一个对象且背景为黑色的图片(img1=cv2.imread('picture.jpg')
)。
请注意,该对象没有黑色像素。
我想像这样将img1
复制到img2
:img2=img1.copy()
但是我想在img2
中将img1
的所有黑色像素(背景)设置为白色。我怎样才能达到这个目标?
最佳答案
这应该起作用:(在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);
使用copyTo和cvtColor。
唯一的问题是,如果输入图像中的背景像素为零。在这种情况下,您可能更喜欢使用洪水填充方法,但是对于您的问题而言可能是过大的了。
编辑:您也可以使用inRange创建蒙版。
关于python - 将图像从黑色像素复制为白色像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28855496/