Niklas Hildebrandt
Niklas Hildebrandt

Reputation: 31

Crop image according to border within the image python

I'm trying to crop an image like this:

image to crop

according to the blue border within the image, so that it has output similar to this:

Desired crop

so that the cropped image consists of the entire image within the borders. I have looked at similar posts and have thought about using cv2.findContours, but struggling with how I can process the image before passing it to the findContours function. Don't know if a threshold should be applied? Any help would be much appreciated.

Upvotes: 3

Views: 1619

Answers (1)

fmw42
fmw42

Reputation: 53277

Here is one way to do that in Python/OpenCV by thresholding on the blue color and then finding the min and max bounds of the white. This method assumes that the blue box is a rectangle aligned with the X and Y image axes.

Input:

enter image description here

import cv2
import numpy as np

# load image
img = cv2.imread("blue_box.jpg")

# get color bounds of blue box
lower =(230,150,60) # lower bound for each channel
upper = (255,190,100) # upper bound for each channel

# create the mask
mask = cv2.inRange(img, lower, upper)

# get bounds of white pixels
white = np.where(mask==255)
xmin, ymin, xmax, ymax = np.min(white[1]), np.min(white[0]), np.max(white[1]), np.max(white[0])
print(xmin,xmax,ymin,ymax)

# crop the image at the bounds
crop = img[ymin:ymax, xmin:xmax]
hh, ww = crop.shape[:2]

# write result to disk
cv2.imwrite("blue_box_mask.jpg", mask)
cv2.imwrite("blue_box_cropped.jpg", crop)

# display it
cv2.imshow("mask", mask)
cv2.imshow("crop", crop)
cv2.waitKey(0)

Threshold image:

enter image description here

Cropped image:

enter image description here

Upvotes: 2

Related Questions