简体   繁体   English

如何仅使用PIL图像有条件地修改每个像素的像素值

[英]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 我想将所有像素(所有r,g,b)的像素值减少100,然后如果将像素值更新为255(所有r,g,b),其中r = g = b且r> 127

I have tried using CV2 and numpy it works fine, however i am asked to do it using pure PIL Image only. 我已经尝试使用CV2和numpy正常工作,但是我被要求仅使用纯PIL图像来做。

The code in CV2/numpy is CV2 / numpy中的代码是

        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 我想要使​​用纯PIL图像的类似代码,不允许导入CV2或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. @IQbrod的答案(更正后)可能会解决当前的问题,但从长远来看效率很低

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. 上面的代码接收一个图像对象(通过Image.open创建),然后使用img.getdata()获得它的像素图,并将其存储在类型为list的变量( data )中。 Then uses list comprehension for modifying pixel values, guided by a condition. 然后在条件的指导下使用列表推导来修改像素值。 And in the end returns the modified image object. 最后返回修改后的图像对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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