Created
March 24, 2022 21:56
-
-
Save ola0x/1c24e7570d52585b65e86dd692a2cdf9 to your computer and use it in GitHub Desktop.
this is to creata a pad around the image if the crop bbox is less than the origin or grater than the image width and height.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
def pad_img_to_fit_bbox(img, x1, x2, y1, y2): | |
img = cv2.copyMakeBorder(img, - min(0, y1), max(y2 - img.shape[0], 0), | |
-min(0, x1), max(x2 - img.shape[1], 0),cv2.BORDER_REPLICATE) | |
y2 += -min(0, y1) | |
y1 += -min(0, y1) | |
x2 += -min(0, x1) | |
x1 += -min(0, x1) | |
return img, x1, x2, y1, y2 | |
def imcrop(img, bbox): | |
x1, y1, x2, y2 = bbox | |
if x1 < 0 or y1 < 0 or x2 > img.shape[1] or y2 > img.shape[0]: | |
img, x1, x2, y1, y2 = pad_img_to_fit_bbox(img, x1, x2, y1, y2) | |
return img[y1:y2, x1:x2, :] | |
im = cv2.imread("image/acc1.png") | |
bbox = -1,-299,200,100 | |
crop_img = imcrop(im,bbox) | |
cv2.imshow("Img", crop_img) | |
cv2.waitKey(0) | |
cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment