Reputation: 73
I am trying to do image contrast without using any python libraries. Personally i feel it's better to learn how to code without using the various libraries to get a better understanding. In my case i am trying to avoid using opencv to contrast an image.
The issue i'm having is TypeError: 'int' object has no attribute '__getitem__'
. Honestly, I'm not quite sure what this error means.
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)
Upvotes: 0
Views: 3117
Reputation: 4548
Your code has a lot of problems in it, but the one you are running into first is that you should be calling img.shape
instead of img.size
but that's really the tip of the iceberg.
I'm not sure what your original intention was, but here is code that works and looks like it's doing something related to contrast (although the colors are changing in strange ways):
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()
Upvotes: 1