[英]How to change particular type of pixel value in a grayscale image in python?
I want to get a grayscale image in which if pixel_value > 250
, then new pixel_value = 250
. 我想获得一个灰度图像, if pixel_value > 250
,则new pixel_value = 250
。
I have tried it on the image 我已经在图像上尝试过
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. 任何解决方案将不胜感激。
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. 您正在处理错误的图像数据-您从x = pixelsNew[j,i][0]
中读取了像素,这是您新创建的图像-尚无Tigerdata。
I prefer to work with RGB - so I can fe 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. 我更喜欢使用RGB-因此我可以微调灰度,以在B等上使用R。如果要对“ LA”图像进行操作,请取消注释“ LA”行并注释“ RGB”行。
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: 您的输入:
thresholded with range(50,250)
: 阈值range(50,250)
:
Disclaimer: Code inspired by: plasmon360's answer to Changing pixels to grayscale using PIL in Python 免责声明:受以下方面启发的代码: plasmon360 对使用Python中的PIL将像素更改为灰度 的答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.