2017-08-14 127 views
1

我正在尝试创建一个用于转换图片中特定像素的RBG值的代码。这是我迄今为止的代码:转换特定的rgb值

所以我已经得到尽可能为像素的新颜色输入新的RGB值,但我很难为实际输入那些像素。谢谢,任何帮助表示赞赏!

+0

用['Image.putpixel()'](http://pillow.readthedocs.io/en/4.2.x/reference/Image.html#PIL.Image.Image.putpixel)。 – martineau

+0

@martineau有关如何格式化image.putpixel变量的想法?我遇到了这个问题。我添加到函数底部的代码如下所示:“”“original.putpixel((coordinates),(new_RGB))”“”“这应该起作用,因为第一个参数是两个笛卡尔坐标,第二个参数是参数是r,g,b值,不知道它为什么不工作 – physicslifter

+0

它取决于打开的图像的格式,如果它是RGB,那么颜色值应该是三个_integers_的序列, (10,2,4)'不''10,2,4“'。黑白图像只需要一个整数值(不是一个序列中只有一个东西),这意味着你不能只使用字符串的'input()'函数返回,你需要在调用'putpixel()'之前将字符串转换为所需的格式。坐标也是如此,除非它们总是需要两个整数值代表x和y的位置,不管图像格式如何。 – martineau

回答

1

这就是我想出的。

from PIL import Image, ImageFilter 


print("enter image file:") 
myimage = input() 

try: 
    original = Image.open(myimage) 
    im = original.load() 
except: 
    print('Invalid file') 
    # print(myimage) 
    # print("The size of the Image is: ") 

print(original.format, original.size, original.mode) 

# pixel_values = list(original.getdata()) 

''' 
for y in range(0, 512): 
    row = "" 
for x in range(0, 512): 
    row = "" 
''' 

print("Enter coordinates of desired pixel in x,y form") 
coordinates = [int(x) for x in input().split(',')] 
x, y = coordinates 
R, G, B = im[x, y] 
print("R,G,B values corresponding with this pixel are:") 
print(R, G, B) 

print("enter new R,G,B values") 
new_RGB = [int(x) for x in input().split(',')] 

r, g, b = new_RGB 

im[x, y] = (r, g, b) 

original.save(myimage) 
+0

我试过这段代码,其中一个问题是,如果x,y坐标值较低(例如我使用15,18并产生一个错误,它会产生一个错误,但你认为[x, y] =(r,g,b)是与image.putpixel相对的方式吗?因为我一直在为后者工作,我会和前者一起玩,看看我是否可以实现它。 – physicslifter

+0

它为我工作(15,18)你可以发布错误代码吗? –

+0

谢谢!!我得到它的工作 – physicslifter