调整边界框的大小和位置,同时保持中心位置

时间:2017-11-30 19:07:15

标签: python image opencv image-processing

我有一堆带有相应边界框坐标(x,y,w,h)的图像。一些边界框是矩形的,所以首先我想让它们成为正方形,同时仍然以感兴趣的区域为中心。使用下面的苹果示例,在茎上有一个边界框,我想将盒子扩展到正方形,同时仍然将它保持在茎杆的中心位置。

square

其次,在我提取出边界框的内容之后,我想通过增加 n 像素的边界框大小并提取然后重复来捕获上下文信息。之后,我想将感兴趣区域的几何中心移动几个像素并重复多个边界框提取。如下图所示,不同颜色的框表示我想要提取的不同框。右图显示了我想要实现的中心小变化。

multiple

我知道如何在numpy中执行此操作,但是有没有更高级别的函数/库可以帮助我定义边界框并对其进行操作?

1 个答案:

答案 0 :(得分:0)

我用这个图像做同样的效果:

enter image description here

代码和评论(作为描述):

#!/usr/bin/python3
# 2017.11.25 17:10:34 CST
# 2017.12.01 11:23:02 CST

import cv2
import numpy as np

## Read and copy 
img = cv2.imread("cat.jpg")
canvas = img.copy()

## set and crop the ROI 
x,y,w,h = bbox = (180, 100, 50, 100)
cv2.rectangle(canvas, (x,y), (x+w,y+h), (0,0,255), 2)
croped = img[y:y+h, x:x+w]
cv2.imshow("croped", croped)

## get the center and the radius
cx = x+w//2
cy = y+h//2
cr  = max(w,h)//2

## set offset, repeat enlarger ROI
dr = 10
for i in range(0,4):
    r = cr+i*dr
    cv2.rectangle(canvas, (cx-r, cy-r), (cx+r, cy+r), (0,255,0), 1)
    croped = img[cy-r:cy+r, cx-r:cx+r]
    cv2.imshow("croped{}".format(i), croped)

## display 
cv2.imshow("source", canvas)
cv2.waitKey()
cv2.destroyAllWindows()

结果:

enter image description here

enter image description here

相关问题