Replace all the colors of a photo except from the existing black and white pixels PYTHON

僤鯓⒐⒋嵵緔 提交于 2019-12-06 11:55:19

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 cv2lib 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 1s with 255s.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!