[英]How to modify the pixel value of each pixel conditionally using PIL Image ONLY
我想將所有像素(所有r,g,b)的像素值減少100,然后如果將像素值更新為255(所有r,g,b),其中r = g = b且r> 127
我已經嘗試使用CV2和numpy正常工作,但是我被要求僅使用純PIL圖像來做。
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
我想要使用純PIL圖像的類似代碼,不允許導入CV2或numpy
這樣的事?
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的答案(更正后)可能會解決當前的問題,但從長遠來看效率很低 。
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
上面的代碼接收一個圖像對象(通過Image.open
創建),然后使用img.getdata()
獲得它的像素圖,並將其存儲在類型為list的變量( data
)中。 然后在條件的指導下使用列表推導來修改像素值。 最后返回修改后的圖像對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.