问题描述
我有这张图片rand-walk-2.png
我想将所有白色像素转换为黑色像素,以便在黑色背景上有一幅红色随机游走的图片,这意味着我不能只反转图像的颜色.我当前的代码只是找到白色像素并将其设置为黑色:
I would like to convert all the white pixels to black pixels, so that there is a picture of a red random walk over a black background, this means I cannot just invert the colors of image. My current code simply finds the white pixels and set them to black:
from PIL import Image
import PIL.ImageOps
import numpy as np
from skimage.io import imsave
import cv2
in_path = 'rand-walk-2.png'
out_path = 'rand-walk-trial.png'
Image = cv2.imread(in_path)
Image2 = np.array(Image, copy=True)
white_px = np.asarray([255, 255, 255])
black_px = np.asarray([0 , 0 , 0 ])
(row, col, _) = Image.shape
for r in xrange(row):
for c in xrange(col):
px = Image[r][c]
if all(px == white_px):
Image2[r][c] = black_px
imsave(out_path, Image2)
但是它产生了这个:
由于某种原因,我无法解释.
for some reason I cannot explain.
推荐答案
原因是该模块 skimage (在您的情况下为函数skimage.io.imsave
)使用RGB颜色顺序,而OpenCV(在您的情况下为函数cv2.imread
)使用臭名昭著使用BGR颜色序列.这样,蓝色和红色就可以与您的脚本互换了.
The reason is that module skimage (in your case function skimage.io.imsave
) uses RGB color sequence, whereas OpenCV (in your case function cv2.imread
) notoriously uses BGR color sequence. So blue and red colors become swapped with your script.
为您提供的两种解决方案是在阅读后直接将图像转换为RGB:
Two solutions for you would be to either convert the image to RGB directly after reading:
Image = cv2.imread(in_path)
Image = cv2.cvtColor(Image, cv2.COLOR_BGR2RGB)
或使用cv2保存输出图像:
Or to save the output image with cv2:
cv2.imwrite(out_path, Image2)
结果:
另一个提供更好输出的解决方案是简单地反转图像:
Another solution, which gives much nicer output, is simply inverting your image:
Image = cv2.imread(in_path)
Image = cv2.bitwise_not(Image)
cv2.imwrite(out_path, Image)
结果:
或者,如果您仍然想要红色,则可以反转,移除绿色通道并交换蓝色和红色:
Or, if you still want red color, you could invert, remove green channel and swap blue and red:
Image = cv2.imread(in_path)
Image = cv2.bitwise_not(Image)
b,g,r = cv2.split(Image)
z = np.zeros_like(g)
Image = cv2.merge((z,z,b))
cv2.imwrite(out_path, Image)
结果:
这篇关于将图像中的所有白色像素转换为黑色像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!