How to change the pixel values of an Image? [duplicate]

一笑奈何 提交于 2019-12-04 05:03:25

The if block should be followed by an else block, so that "normal" pixels that do not meet your criteria retain their original values.

from PIL import Image
im = Image.open('leaf.jpg')
pixelMap = im.load()

img = Image.new( im.mode, im.size)
pixelsNew = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        if 205 in pixelMap[i,j]:
            pixelMap[i,j] = (0,0,0,255)
        else:
            pixelsNew[i,j] = pixelMap[i,j]
img.show()

The above code gave me the following results:

Input image

Output image

You have made a silly mistake. In Line 6 You have written pixelsNew = im.load() instead of pixelsNew = img.load() This should work now.

from PIL import Image
im = Image.open('nuvfits1.png')
pixelMap = im.load()

img = Image.new( im.mode, im.size)
pixelsNew = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        if 205 in pixelMap[i,j]:
           pixelMap[i,j] = (0,0,0,255)
        pixelsNew[i,j] = pixelMap[i,j]
im.close()
img.show()       
img.save("out.tif") 
img.close()

You basically need a new image with the noise removed, which is pixelsNew. So whenever you find such a case in pixelMap if 205 in pixelMap[i,j] then set that corresponding value as 0 in pixelsNew pixelNew[i,j] = (0, 0, 0, 255). OTHERWISE just copy the pixel value from pixelMap pixelsNew[i,j] = pixelMap[i,j]

from PIL import Image
im = Image.open('nuvfits1.png')
pixelMap = im.load()

img = Image.new( im.mode, im.size)
pixelsNew = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        if 205 in pixelMap[i,j]:
            pixelsNew[i,j] = (0,0,0,255)
        else:
            pixelsNew[i,j] = pixelMap[i,j]
im.close()
img.show()       
img.save("out.tif") 
img.close()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!