我正在尝试绘制纵横比为3:2的矩形。
我正在使用OpenCV来检测图像中的对象。因此,从输出值中,我正在绘制一个具有最小X,最小Y,最大X,最大Y的矩形。现在我需要使该矩形从起点开始具有3:2的纵横比,即最小x和最小Y.
It should not go beyond the original image max X and max Y and the rectangle should not be lesser than existing rectangle around the detected objects.
最佳答案
这是解决此问题的一种方法:
# determine the y / x length of the rectangle
len_X = maxX - minX
len_Y = maxY - minY
# determine the largest side, this will be the 3 in the aspect ratio
if len_X > len_Y:
# check if the shorter side is larger than a 3:2 ration
if len_Y > len_X * (3/2):
# if so, increase larger side to 3:2 ratio
len_X = len_Y * 1.5
else:
# else, increase shorter side to 3:2 ratio
len_Y = len_X * (3/2)
else:
# same as above
if len_X > len_Y * (3/2):
len_Y = len_X * 1.5
else:
len_X = len_Y * (3/2)
# if the rectangle exceeds the image, constrain the rectangle
# other option (commented): move the starting position
if minX + len_X > img.shape[1]:
len_X = img.shape[1]-minX
#minX = img.shape[1]-len_X
if minY + len_Y > img.shape[0]:
len_Y = img.shape[0]-minY
#minY = img.shape[0]-len_Y
# draw the rectangle
cv2.rectangle(img, (minX, minY), (minX + len_X, minY + len_Y), (0,0,255),1)
关于python - 在图像上以3:2长宽比绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54722976/