Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am working on an Image Processing Project and I am a beginner at Python and using PIL. Any help would be appreciated.

So, what I am doing is, I have an image of space with stars and noise. What I want to do is keep only the brighter pixels and filter out the dull ones. For now, this is my basic step at trying to remove the noise. After studying the image data, I found that values of 205 are quite possibly the ones I want to keep the threshold at.

So what I am doing in the code is, open the image and change the pixel values containing 205 to black. Here is the code for the same:

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

img = Image.new( im.mode, im.size)
pixelsNew = im.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()

The problem is, that the resultant image is just a plain white screen. What have I done wrong?

like image 943
Manshi Sanghai Avatar asked Jul 05 '16 08:07

Manshi Sanghai


1 Answers

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

Input

Output image

Output

like image 79
essbee Avatar answered Oct 07 '22 00:10

essbee