Reputation: 245
import ImageFilter
import pygame
import numpy
from PIL import Image
import PIL.Image
imageFile='C:\Users\Abhi\Desktop\cbir-p\New folder\gray_image.jpg'
size = Image.open(imageFile).size
im2=Image.open(imageFile)
a=[]
for x in range(size[0]):
a.append([])
for y in range(size[1]):
inten=im2.getpixel((x,y))
a[x].append(inten)
#inten=im2.getpixel((116,143))
#print inten
for item in a:
item.insert(0,0)
item.append(0)
#print a
a.insert(0,[0]*len(a[0]))
a.append([0]*len(a[0]))
#print len(a)
#for item in a:
#print len(item)
b=[]
#print a[1:-1]
for i in range(1,len(a)-1):
b.append([])
for j in range(1,len(a[0])-1):
b[i-1].append((a[i-1][j-1]+a[i-1][j]+a[i-1][j+1]+a[i][j-1]+a[i][j]+a[i][j+1]+a[i+1][j-1]+a[i+1][j]+a[i+1][j+1])/9)
#print b[81][140]
c=numpy.array(b)
#print c
i1 = Image.fromarray(c)
i1.show()
#i1.save('gray.png')
I have blurred the image by finding the average value of its 8 neighbors and also the current pixel. When i try to print the image , i'm getting a blurred image but it is rotated leftward. Can anyone help me why its rotated leftward .Image is a gray-scale image.
Upvotes: 1
Views: 72
Reputation: 879113
2D numpy arrays of shape (h, w)
can be thought of as having h
rows and w
columns.
But PIL images with size (w, h)
are w
pixels wide and h
pixels high.
So the two data structures flip-flop the order of the rows and columns. If you trace through your code you'll see
a[x].append(inten)
is placing x
coordinates along the rows of a
, thus rotating the image.
The easiest way to fix your code would be to transpose c
:
c=numpy.array(b).T
But also note there are easier ways to blur an image:
Using PIL:
import ImageFilter
import numpy as np
import Image
imageFile='C:\Users\Abhi\Desktop\cbir-p\New folder\gray_image.jpg'
img = Image.open(FILENAME, 'r').convert('RGB')
img_blur = img.filter(ImageFilter.BLUR)
img_blur.save('/tmp/pil_blur.png')
Or, if you have scipy installed:
import scipy.ndimage as ndimage
arr = np.asarray(img)
arr_blur = ndimage.gaussian_filter(arr, sigma=(3, 3, 0), order = 0)
img2_blur = Image.fromarray(arr_blur.astype('uint8'), 'RGB')
img2_blur.save('/tmp/scipy_blur.png')
Upvotes: 3