简体   繁体   English

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

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

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. 我是python的初学者,我想通过一种方法将照片的所有像素更改为白色,但照片中已有的白色或黑色像素除外。 I tried to use PIL but I couldn't find it. 我尝试使用PIL,但找不到。 Thanks! 谢谢!

Assuming you have access to matplotlib and are willing to use it: 假设您有权使用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)

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. 另外,请确保输入为[0,1]格式。 If it is in [0,255] modify the above 1 s with 255 s. 如果在[0,255]中,则将上述1 s修改为255 s。

Edit: this solution works for RGB, with no alpha. 编辑:此解决方案适用于RGB,没有alpha。 If you have an alpha, you might need to modify, depending on your requirements. 如果您有Alpha,则可能需要根据需要进行修改。

Hope this helps. 希望这可以帮助。

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) 如果是这样,那么下面的工作(注意:它期望在您的计算机上安装了cv2 lib)

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM