Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/svn/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何仅使用PIL图像有条件地修改每个像素的像素值_Python_Python Imaging Library - Fatal编程技术网

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

Python 如何仅使用PIL图像有条件地修改每个像素的像素值,python,python-imaging-library,Python,Python Imaging Library,我想将所有像素的像素值减少100(所有r、g、b) 然后,如果将像素值更新为255(全部r、g、b),其中r=g=b且r>127 我已经尝试使用CV2和numpy,它工作得很好,但是我被要求只使用纯PIL图像 CV2/numpy中的代码是 def getCorrectedImage(im): 打印类型(im),im形状 乘数=np.one(im.shape,dtype=“uint8”)*100 outImage=cv2.减法(im,乘法器) 高度、宽度、通道=outImage.shape 对于范

我想将所有像素的像素值减少100(所有r、g、b) 然后,如果将像素值更新为255(全部r、g、b),其中r=g=b且r>127

我已经尝试使用CV2和numpy,它工作得很好,但是我被要求只使用纯PIL图像

CV2/numpy中的代码是

def getCorrectedImage(im):
打印类型(im),im形状
乘数=np.one(im.shape,dtype=“uint8”)*100
outImage=cv2.减法(im,乘法器)
高度、宽度、通道=outImage.shape
对于范围内的x(0,高度):
对于范围(0,宽度)内的y:
b、 g,r=outImage[x,y]
如果b>128,g>128,r>128:
outImage[x,y]=(255,255,255)
返回输出图像
我想要使用纯PIL图像的类似代码,不允许我导入CV2或numpy之类的东西

def正确(pImg):
vImg=pImg
宽度、高度=vImg.size
对于范围内的x(宽度):
对于范围内的y(高度):
像素=(对于vImg.getpixel((x,y))中的像素,pix为-100)
如果(像素[0]>127&&pixel.count(像素[0])==3):
像素=(255,255,255)
vImg.putpixel((x,y),pixel)
回程振动
类似的东西

def正确(pImg):
vImg=pImg
宽度、高度=vImg.size
对于范围内的x(宽度):
对于范围内的y(高度):
像素=(对于vImg.getpixel((x,y))中的像素,pix为-100)
如果(像素[0]>127&&pixel.count(像素[0])==3):
像素=(255,255,255)
vImg.putpixel((x,y),pixel)
回程振动
@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()
获得它的像素图,并将其存储在类型列表的变量(
data
)中。然后使用列表理解在条件的指导下修改像素值。最后返回修改后的图像对象。

@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()
获得它的像素图,并将其存储在类型列表的变量(
data
)中。然后使用列表理解在条件的指导下修改像素值。最后返回修改后的图像对象。

PIL
可以为此使用
numpy
数组。
image.getpixel()
image.putpixel()
或获取全部为
image.getdata()
PIL可以为此使用
numpy
数组。
image.getpixel()
image.putpixel()
或get all as
image.getdata()
python不使用
&&
表示逻辑and,而是使用
。其次,您的代码中存在很多错误,因此我建议您在发布答案之前纠正这些错误(并通过在不同的图像上运行程序来检查程序)。python不使用
&
表示逻辑and,而是使用
。其次,你的代码中存在很多错误,所以我建议你在发布答案之前纠正它们(并通过在不同的图像上运行它来检查程序)。