Reputation:
My all images have Region of interest which is bounded by doted white lines. I want to crop only those portion.
I got one idea that find minimum(x,y) which is top left corner and find maximum(x,y) which is bottom right corner and crop the area?
We can get Pixel value from PIL library
Upvotes: 0
Views: 3499
Reputation:
from PIL import Image
from IPython.display import display, HTML
from IPython.display import Image as displayImage
img=Image.open('image.png')
imag_rgb = img.convert('RGB')
width, height = imag_rgb.size
print (width, height)
for pixel_x in range(width):
for pixel_y in range(height):
r, g, b = rgb_img.getpixel((pixel_x, pixel_y))
if(r == 255 and g == 255 and b == 255):
min_pixel_x = pixel_x
min_pixel_y = pixel_y
max_pixel_x = pixel_x
max_pixel_y = pixel_y
print (pixel_x, pixel_y)
cropped_image = img.crop((min_pixel_x, min_pixel_y,max_pixel_x + 1, max_pixel_y + 1))
#### +1 because of first x,y is 0,0
display(cropped_image)
Upvotes: 1
Reputation: 1585
To read a pixel value in PIL
from PIL import Image
im = Image.open(imagename)
pix = im.load()
print (pix[0,0])
This will return the first pixel in the first row.
If you wanted to read all pixels you could do something like this.
x, y = im.size
for i in x:
for j in y:
print (pix[i,j])
Upvotes: 0
Reputation: 72
It's easy to crop images using opencv2. Try this link
ball = img[280:340, 330:390]
since Image is a 2D array you can crop with above line.
Upvotes: 0