替换照片中除现有黑白像素外的所有颜色

3
我希望有一种方法可以将照片中除了已经是白色或黑色的像素外的所有像素变成白色。
我尝试使用PIL,但无法找到相应的功能。

你会使用matplotlib吗? - Tacratis
2个回答

7
我希望您能将照片中的所有像素更改为白色,除了已经存在于照片中的白色或黑色像素。所以基本上您想要将所有像素更改为白色,除了黑色,对吗?如果是这样,那么下面的工作就可以实现(注意:它需要在您的计算机上安装cv2库)。
import cv2
import numpy as np

img = cv2.imread('my_img.jpeg')
img[img != 0] = 255 # change everything to white where pixel is not black
cv2.imwrite('my_img2.jpeg', img)

是的,这部分是我想做的。我想改变所有既不是黑色也不是白色的像素。所以,如果像素颜色与黑色或白色不同,则更改颜色。我尝试了您的代码:img[img != 0 and != 255] = 177,但它显示出and的错误。我还想知道是否可以将它们变成透明的,而不是改变为固定颜色(例如在此示例中为177)。非常感谢! - Carlos
2
在这种情况下,您可以使用按位&,例如img[(img != 0) & (img != 255)] = 177 - sagarr
1
昨天它运行得完美无缺,但今天却出现了这个错误。我该怎么办?TypeError:'NoneType'对象不支持项目分配。 - Carlos
它能用一些照片,但对于其他照片就不行。你有什么想法吗? - Carlos
1
针对 TypeError: 'NoneType' object does not support item assignment 错误,只需检查图像名称是否正确即可。在我的情况下,我在图像名称中犯了一个错误,导致出现了相同的错误。(我将 .jpg 写成了 .jpgg) - Karthic Srinivasan

1
假设您可以访问matplotlib并愿意使用它:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# read the image pixels and saves them as a numpy array
image = mpimg.imread('<your image>')

# see original image (just for testing)
plt.imshow(image)
plt.show()

# loop through all pixels, and replace those that are not strict white or black with white
for x in range(image.shape[0]):
    for y in range(image.shape[1]):
        if (image[x,y]!=0).all() and (image[x,y]!=1).all():
            image[x,y] = [1,1,1]  

# see modified image (to make sure this is what you need)
plt.imshow(image)
plt.show()

# save image
mpimg.imsave('<new name>',image)

你可能可以将此向量化,但根据性能要求,我发现这更易读。 另外,请确保输入格式为[0,1]。如果它是[0,255],请使用255替换上面的1
注意:此解决方案适用于RGB,不带alpha通道。如果您有alpha通道,则可能需要进行修改,具体取决于您的要求。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接