我希望有一种方法可以将照片中除了已经是白色或黑色的像素外的所有像素变成白色。
我尝试使用PIL,但无法找到相应的功能。
我尝试使用PIL,但无法找到相应的功能。
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) & (img != 255)] = 177
。 - sagarrTypeError: 'NoneType' object does not support item assignment
错误,只需检查图像名称是否正确即可。在我的情况下,我在图像名称中犯了一个错误,导致出现了相同的错误。(我将 .jpg 写成了 .jpgg) - Karthic Srinivasanimport 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
。