更改PIL中的像素颜色值 [英] Changing pixel color value in PIL

查看:107
本文介绍了更改PIL中的像素颜色值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在python中更改图像的像素颜色.除了像素值(255,0,0)红色外,我需要将每个像素颜色值更改为黑色(0,0,0).我尝试了以下代码,但没有帮助.

I need to change pixel color of an image in python. Except for the pixel value (255, 0, 0) red I need to change every pixel color value into black (0, 0, 0). I tried the following code but it doesn't helped.

from PIL import Image
im = Image.open('A:\ex1.jpg')
for pixel in im.getdata():
    if pixel == (255,0,0):
        print "Red coloured pixel"
    else:
        pixel = [0, 0, 0]

推荐答案

请参阅以下Wikibook: https ://en.wikibooks.org/wiki/Python_Imaging_Library/Editing_Pixels

See this wikibook: https://en.wikibooks.org/wiki/Python_Imaging_Library/Editing_Pixels

修改该代码以适合您的问题:

Modifying that code to fit your problem:

pixels = img.load() # create the pixel map

for i in range(img.size[0]): # for every pixel:
    for j in range(img.size[1]):
        if pixels[i,j] != (255, 0, 0):
            # change to black if not red
            pixels[i,j] = (0, 0 ,0)

这篇关于更改PIL中的像素颜色值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆