I'm a beginner in python and i would like the way to change all of the pixels of a photo to white, except the pixels that white or black that were already in the photo. I tried to use PIL but I couldn't find it. Thanks!
i would like the way to change all of the pixels of a photo to white, except the pixels that white or black that were already in the photo.
So basically you want to change all pixels to white except black, right? If so, then below work (note: it expect cv2
lib is installed on your machine)
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)
Assuming you have access to matplotlib and are willing to use it:
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)
You can probably vectorize this, but I find this more readable, depends on your preformance requirements.
Also, make sure the input is in [0,1] format. If it is in [0,255] modify the above 1
s with 255
s.
Edit: this solution works for RGB, with no alpha. If you have an alpha, you might need to modify, depending on your requirements.
Hope this helps.
来源:https://stackoverflow.com/questions/55192340/replace-all-the-colors-of-a-photo-except-from-the-existing-black-and-white-pixel