2
votes

Requirement is to crop region of interest from binary image.

I need a rectangle image from a binary image by removing the extra space around the region of interest.

For example: From this Original image i want only the region of interest marked with yellow color rectangle.

Note: Yellow color rectangle is just for the reference and it is not present in the image that will be processed.

I tried the following python code but it is not giving the required output.

from PIL import Image
from skimage.io import imread
from skimage.morphology import convex_hull_image
import numpy as np
from matplotlib import pyplot as plt
from skimage import io
from skimage.color import rgb2gray
im = imread('binaryImageEdited.png')
plt.imshow(im)
plt.title('input image')
plt.show()
# create a binary image
im1 = 1 - rgb2gray(im)
threshold = 0.8
im1[im1 <= threshold] = 0
im1[im1 > threshold] = 1
chull = convex_hull_image(im1)
plt.imshow(chull)
plt.title('convex hull in the binary image')
plt.show()
imageBox = Image.fromarray((chull*255).astype(np.uint8)).getbbox()
cropped = Image.fromarray(im).crop(imageBox)
cropped.save('L_2d_cropped.png')
plt.imshow(cropped)
plt.show()

Thank you.

2
Did my answer sort out your problem? If so, please consider accepting it as your answer - by clicking the hollow tick/checkmark beside the vote count. If not, please say what didn't work so that I, or someone else, can assist you further. Thanks. meta.stackexchange.com/questions/5234/…Mark Setchell

2 Answers

1
votes

Your image is not actually binary on account of two things:

  • firstly, it has 26 colours, and
  • secondly it has an (entirely unnecessary) alpha channel.

You can trim it like this:

#!/usr/bin/env python3

from PIL import Image, ImageOps

# Open image and ensure greysale and discard useless alpha channel
im = Image.open("thing.png").convert('L')

# Threshold and invert image as not actually binary
thresh = im.point(lambda p: p < 64 and 255)

# Get bounding box of thresholded image
bbox1 = thresh.getbbox()
crop1 = thresh.crop(bbox1)

# Invert and crop again
crop1n = ImageOps.invert(crop1)
bbox2  = crop1n.getbbox()
crop2  = crop1.crop(bbox2)  # You don't actually need this - it's just for debug

# Trim original, unthresholded, uninverted image to the two bounding boxes
result = im.crop(bbox1).crop(bbox2)
result.save('result.png')

enter image description here

0
votes

even i have similar problem. Also it would be helpful if image saved is in 32X32 px.