Makogan
Makogan

Reputation: 9548

Opencv, how to overcrop an image?

I have a set of arbitrary images. Half the images are pictures, half are masks defining ROIS.

In the current version of my program I use the ROI to crop the image (i.e I extract the rectangle in the image matching the bounding box of the ROI mask). The problem is, the ROI mask isn't perfect and it's better to over predict than under predict in my case.

So I want to copy more than the ROI rectangle, but if I do this, I may be trying to crop out of the image.

i.e:

 x, y, w, h = cv2.boundingRect(mask_contour)
 img = img[int(y-h*0.05):int(y + h * 1.05), int(x-w*0.05):int(x + w * 1.05)]

can fail because it tries to access out of bounds pixels. I could just clamp the values, but I wanted to know if there is a better approach

Upvotes: 0

Views: 611

Answers (2)

Stephen Meschke
Stephen Meschke

Reputation: 2940

You can add a boarder using OpenCV

lena with boarder

import cv2 as cv
import random
src = cv.imread('/home/stephen/lenna.png')
borderType = cv.BORDER_REPLICATE
boarderSize = .5
top = int(boarderSize * src.shape[0])  # shape[0] = rows
bottom = top
left = int(boarderSize * src.shape[1])  # shape[1] = cols
right = left    
value = [random.randint(0,255), random.randint(0,255), random.randint(0,255)]
dst = cv.copyMakeBorder(src, top, bottom, left, right, borderType, None, value)
cv.imshow('img', dst)
c = cv.waitKey(0)

Upvotes: 2

v.coder
v.coder

Reputation: 1932

Maybe you could try to limit the coordinates beforehand. Please see the code below:

[ymin, ymax] = [max(0,int(y-h*0.05)), min(h, int(y+h*1.05))]
[xmin, xmax] = [max(0,int(x-w*1.05)), min(w, int(x+w*1.05))]
img = img[ymin:ymax, xmin:xmax]

Upvotes: 0

Related Questions