调整图像的对比度

时间:2017-03-12 02:02:25

标签: python

我试图在不使用任何python库的情况下进行图像对比。就个人而言,我觉得如果不使用各种库来更好地理解如何编写代码会更好。在我的情况下,我试图避免使用opencv来对比图像。

我遇到的问题是TypeError: 'int' object has no attribute '__getitem__'。老实说,我不太清楚这个错误意味着什么。

import matplotlib.pylab as plt
import matplotlib.image as mpimg
import numpy as np

img = np.uint8(mpimg.imread('igloo.png'))

img = np.uint8((0.2126* img[:,:,0]) + \
    np.uint8(0.7152 * img[:,:,1]) +\
         np.uint8(0.0722 * img[:,:,2]))

def img_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))

tam = img_contrast(img)

plt.imshow(tam)

1 个答案:

答案 0 :(得分:1)

您的代码中存在很多问题,但您首先遇到的问题是您应该调用img.shape而不是img.size,但这确实是冰山一角。

我不确定你的初衷是什么,但这里的代码是有效的,看起来它正在做与对比相关的事情(虽然颜色在奇怪的方式变化):

CODE:

import pylab as plt
import matplotlib.image as mpimg
import numpy as np


#Read in the image and make it ints for some reason
#(Normally they are floats between 0 and 1 which is why mult by 256)
img = 255*mpimg.imread('igloo.png')

img[:,:,0] = 0.2126*img[:,:,0] #Red
img[:,:,1] = 0.7152*img[:,:,1] #Green
img[:,:,2] = 0.0722*img[:,:,2] #Blue
                               #Last channel is Alpha (transparency)

def img_contrast(img):
    rows,cols,channels = img.shape
    for x in range(rows):
        for y in range(cols):
            if img[x,y,:3].mean > 128:
                (r, g, b) = img[x,y,:3]
                img[x,y,:3] = (r+80, g+80, b+80)
            else:
                (r, g, b) = img[x,y,:3]
                img[x,y,:3] = (r-80, g-80, b-80)

    return img

#Pass the numpy img through the function, then convert it back to floats between 0 and 1
tam = img_contrast(img)
plt.imshow(tam/255)
plt.show()

图片之前: Before

图片后: After