简体   繁体   中英

How to modify the pixel value of each pixel conditionally using PIL Image ONLY

I want to reduce the pixel value by 100 for all pixels (all r,g,b) then if update the pixel values to 255 (all r,g,b) where the r=g=b and r > 127

I have tried using CV2 and numpy it works fine, however i am asked to do it using pure PIL Image only.

The code in CV2/numpy is

        def getCorrectedImage(im):
            print type(im), im.shape
            multiplier = np.ones(im.shape, dtype="uint8") * 100
                outImage = cv2.subtract(im, multiplier)
                height, width, channel = outImage.shape
                for x in range(0, height):
                    for y in range(0, width):
                        b, g, r = outImage[x, y]
                        if b > 128 and g > 128 and r > 128:
                            outImage[x, y] = (255, 255, 255)
                return outImage

I want similar code using pure PIL Image, I am not allowed to import CV2 or numpy

Something like that ?

def correct(pImg):
  vImg = pImg
  width, height = vImg.size
  for x in range(width):
    for y in range(height):
      pixel = (pix - 100 for pix in vImg.getpixel((x, y)))
      if (pixel[0] > 127 && pixel.count(pixel[0]) == 3):
        pixel = (255, 255, 255)
      vImg.putpixel((x,y),pixel)
  return vImg

@IQbrod 's answer (after rectification) may work for the immediate problem, but is quite inefficient in the long run.

def getCorrectedImage(img):
    data = list(img.getdata())

    new_data = [(255, 255, 255)  if x[0]== x[1] and x[1] == x[2] and x[0] > 127 else (x[0]-100, x[1]-100, x[2]-100) for x in data]

    img.putdata(new_data)
    return img

The above code, takes in an image object (created via Image.open ) and then obtains it's pixel map using img.getdata() and stores it in a variable ( data ) of type list. Then uses list comprehension for modifying pixel values, guided by a condition. And in the end returns the modified image object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM