繁体   English   中英

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

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

我是python的初学者,我想通过一种方法将照片的所有像素更改为白色,但照片中已有的白色或黑色像素除外。 我尝试使用PIL,但找不到。 谢谢!

假设您有权使用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]中,则将上述1 s修改为255 s。

编辑:此解决方案适用于RGB,没有alpha。 如果您有Alpha,则可能需要根据需要进行修改。

希望这可以帮助。

我想将照片的所有像素更改为白色的方法,除了照片中已经存在的白色或黑色像素之外。

所以基本上您想将除黑色以外的所有像素都更改为白色,对吧? 如果是这样,那么下面的工作(注意:它期望在您的计算机上安装了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