簡體   English   中英

如何在python的灰度圖像中更改特定類型的像素值?

[英]How to change particular type of pixel value in a grayscale image in python?

我想獲得一個灰度圖像, if pixel_value > 250 ,則new pixel_value = 250
我已經在圖像上嘗試過

在此處輸入圖片說明

如下所示:

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")

但這行不通。 任何解決方案將不勝感激。

使用更好的名稱,並無意跳過加載/存儲/重新加載圖像。

您正在處理錯誤的圖像數據-您從x = pixelsNew[j,i][0]中讀取了像素,這是您新創建的圖像-尚無Tigerdata。

我更喜歡使用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")

您的輸入:

老虎輸入

閾值range(50,250)

虎門虎50-250


免責聲明:受以下方面啟發的代碼: plasmon360 對使用Python中的PIL將像素更改為灰度 的答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM