chickflick91
chickflick91

Reputation: 63

How to analyze only a part of an image?

I want to analyse a specific part of an image, as an example I'd like to focus on the bottom right 200x200 section and count all the black pixels, so far I have:

im1 = Image.open(path)
rgb_im1 = im1.convert('RGB')
for pixel in rgb_im1.getdata():

Upvotes: 2

Views: 575

Answers (3)

Mark Setchell
Mark Setchell

Reputation: 207385

Whilst you could do this with cropping and a pair of for loops, that is really slow and not ideal.

I would suggest you use Numpy as it is very commonly available, very powerful and very fast.

Here's a 400x300 black rectangle with a 1-pixel red border:

enter image description here

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Open the image and make into Numpy array
im = Image.open('image.png')
ni = np.array(im)

# Declare an ROI - Region of Interest as the bottom-right 200x200 pixels
# This is called "Numpy slicing" and is near-instantaneous https://www.tutorialspoint.com/numpy/numpy_indexing_and_slicing.htm
ROI = ni[-200:,-200:]

# Calculate total area of ROI and subtract non-zero pixels to get number of zero pixels
# Numpy.count_nonzero() is highly optimised and extremely fast
black = 200*200 - np.count_nonzero(ROI)
print(f'Black pixel total: {black}')

Sample Output

Black pixel total: 39601

Yes, you can make it shorter, for example:

h, w = 200,200 
im = np.array(Image.open('image.png'))
black = h*w - np.count_nonzero(ni[-h:,-w:])

If you want to debug it, you can take the ROI and make it into a PIL Image which you can then display. So just use this line anywhere after you make the ROI:

# Display image to check
Image.fromarray(ROI).show()

enter image description here

Upvotes: 1

Shahir Ansari
Shahir Ansari

Reputation: 1848

from PIL import Image
img = Image.open("ImageName.jpg")
crop_area = (a,b,c,d)
cropped_img = img.crop(crop_area)

Upvotes: 0

Vasu Deo.S
Vasu Deo.S

Reputation: 1850

You can try cropping the Image to the specific part that you want:-

img = Image.open(r"Image_location")
x,y = img.size
img = img.crop((x-200, y-200, x, y))

The above code takes an input image, and crops it to its bottom right 200x200 pixels. (make sure the image dimensions are more then 200x200, otherwise an error will occur)

Original Image:-

enter image description here

Image after Cropping:-

enter image description here

You can then use this cropped image, to count the number of black pixels, where it depends on your use case what you consider as a BLACK pixel (a discrete value like (0, 0, 0) or a range/threshold (0-15, 0-15, 0-15)).

P.S.:- The final Image will always have a dimension of 200x200 pixels.

Upvotes: 1

Related Questions