0

I want to get a grayscale image in which if pixel_value > 250, then new pixel_value = 250.
I have tried it on the image

enter image description here

like below:

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")

But it does not working. Any solution will be appreciated.

MarianD
  • 13,096
  • 12
  • 42
  • 54
MKS
  • 149
  • 1
  • 5

1 Answers1

0

Use better names and skip loading/storing/reloading images for no purpose.

You are working on the wrong images data - you read the pixel from x = pixelsNew[j,i][0] which is your newly created image - it has no tigerdata in it yet.

I prefer to work with RGB - so I can f.e. tune the grayscaling to use R over B etc. If you'd rather operate on "LA" images, uncomment the "LA" lines and comment the "RGB" lines.

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")

Your input:

tiger input

thresholded with range(50,250):

thresholded tiger 50-250


Disclaimer: Code inspired by: plasmon360's answer to Changing pixels to grayscale using PIL in Python

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69