如何在python的灰度图像中更改特定类型的像素值?

时间:2018-08-05 08:38:02

标签: python python-2.7 pixels grayscale

我想得到一个灰度图像,其中if pixel_value > 250,然后是new pixel_value = 250
我已经在图片上尝试过

enter image description here

如下所示:

from PIL import Image
cols = []
img = Image.open("tiger.jpg") 
img1=img.convert("LA")
img1.save("newImage.png")
img2 = Image.open("newImage.png")
columnsize,rowsize= img2.size
imgconv = Image.new( img2.mode, img2.size) #create new image same size with original image
pixelsNew = imgconv.load() 


for i in range(rowsize):
    for j in range(columnsize):
        x=pixelsNew[j,i][0]
        if x>250:
            pixelsNew[j,i][0]=250
imgconv.save("newImage2.png")

但是它不起作用。任何解决方案将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用更好的名称,并无意跳过加载/存储/重新加载图像。

您正在处理错误的图像数据-您从x = pixelsNew[j,i][0]中读取了像素,它是您新创建的图像-尚无Tigerdata。

我更喜欢使用RGB-所以我可以调整灰度以在B等上使用R。如果要对“ LA”图像进行操作,请取消注释“ LA”行并注释“ RGB”行。

from PIL import Image

def grayscale(picture, thresh):
    """Grayscale converts picture, assures resulting pictures are 
    inside range thres by limiting lowest/highest values inside range"""
    res = Image.new(picture.mode, picture.size)
    width, height = picture.size

    minT = min(thresh)
    maxT = max(thresh)
    for i in range(0, width):
        for j in range(0, height):
            pixel = picture.getpixel((i,j))
            a = int( (pixel[0] + pixel[1] + pixel[2]) / 3)   # RGB
            # a = pixel[0]                                   # LA

            a = a if a in thresh else (minT if a < minT else maxT)

            res.putpixel((i,j),(a,a,a))                      # RGB
            # res.putpixel((i,j),(a))                        # LA
    res.show()
    return res # return converted image for whatever (saving f.e.)

tiger = Image.open(r"tiger.jpg").convert("RGB")
# tiger = Image.open(r"tiger.jpg").convert("LA")
gray = grayscale(tiger, thresh = range(50,200) )
gray.save("newImage.png")

您的输入:

tiger input

range(50,250)为阈值:

thresholded tiger 50-250


免责声明:代码受plasmon360's answerChanging pixels to grayscale using PIL in Python

的启发