[英]Python - Changing An Image's Contrast With For-Loop
我正在嘗試創建一個for循環函數,它將遍歷每個像素以增加圖像的對比度。 我覺得我很接近,但現在圖像只是變亮了。 如果可能的話,盡量密切關注我已經制定的內容(僅供參考,我試圖避免像OpenCV這樣的庫)。 謝謝你的貢獻。
def contrast(img):
for x in range(img.size[0]):
for y in range(img.size[1]):
if (x, y) > 128:
(r, g, b) = img.getpixel((x, y))
img.putpixel((x, y), (r+80, g+80, b+80))
else:
if(x, y) < 128:
(r, g, b) = img.getpixel((x, y))
img.putpixel((x, y), (r-80, g-80, b-80))
這些線:
if (x, y) > 128:
應該將像素的亮度與128進行比較,而不是像素坐標。
您遇到的問題是(x, y) > 128
將元組與單個值進行比較,這可能不是您想要的。 另一個問題是img.getpixel((x, y))
返回RGB圖像的三個獨立顏色分量的元組,而不是像素的亮度。
您需要的是一種圖像處理技術,它將改變彩色圖像的對比度。 我發現了一篇題為“ 圖像處理算法第5部分:對比度調整 ”的文章,該文章描述了一種簡單的方法。
這是使用pillow
版PIL
(Python Imaging Library)模塊的一個實現:
from PIL import Image
# level should be in range of -255 to +255 to decrease or increase contrast
def change_contrast(img, level):
def truncate(v):
return 0 if v < 0 else 255 if v > 255 else v
if Image.isStringType(img): # file path?
img = Image.open(img)
if img.mode not in ['RGB', 'RGBA']:
raise TypeError('Unsupported source image mode: {}'.format(img.mode))
img.load()
factor = (259 * (level+255)) / (255 * (259-level))
for x in range(img.size[0]):
for y in range(img.size[1]):
color = img.getpixel((x, y))
new_color = tuple(truncate(factor * (c-128) + 128) for c in color)
img.putpixel((x, y), new_color)
return img
result = change_contrast('test_image1.jpg', 128)
result.save('test_image1_output.jpg')
print('done')
這是測試運行的結果,我在左邊顯示了前面的圖像,在右邊顯示了生成的圖像 - 它看起來像是有效的:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.