ROBlackSnail
ROBlackSnail

Reputation: 109

Python 3.5 - Pillow - Pixel Acces

I want to write a program that compares 2 images (o small one, and a bigger one) to check if the small one is within the big one.

Knowing that an image can be compared to an array , i have written the following algorithm :

big_image = [
    [1,2,3,4,5,6,7,8,9],
    [10,11]
]

small_image = [
    [1,2],
    [10,11]
]
big_result = []
def check(small_image,  big_image):
    for i in range(len(small_image)):
        for j in range(len(small_image[i])):
            if small_image[i][j] ==  big_image[i][j]:
                result = (i,j)
                big_result.append(result)
    return(big_result)

print(check(small_image, big_image))

It printed out : [(0, 0), (0, 1), (1, 0), (1, 1)] , as intended .

After that I installed the Pillow module to test the algorithm on 2 actual images (.bmp format) .

My question is how do I access the pixels in the image and how do I get the image.width and the image.height so I can test my algorithm.

I did checked the official pillow tutorial (http://pillow.readthedocs.io/en/3.1.x/handbook/tutorial.html) , but all I could find is how to turn around and image , crop it and such .

Upvotes: 1

Views: 1635

Answers (2)

tomcy
tomcy

Reputation: 455

You may use width, height = im.size to find out the width and height like the following example:

from PIL import Image
im = Image.open("lena.bmp")
width, height = im.size
print(width, height)

You may find more example according to this

Upvotes: 0

EriktheRed
EriktheRed

Reputation: 584

For the image dimensions you can do:

import PIL
from PIL import Image

img = Image.open('Imagename.jpg').convert('RGB')
width, height = img.size

To access pixels, PIL has .load(), like this:

pixels = img.load()
for x in range(width):
    for y in range(height):
        pixels[x, y] = (0, 100, 200) #an rgb value
img.show()

Upvotes: 2

Related Questions