python - 在图像上以3:2长宽比绘制矩形

标签 python opencv image-processing

我正在尝试绘制纵横比为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/

相关文章:

python - 如何找到图像的填充大小?

ios - 如何使用 CoreGraphics 重新着色图像?

image-processing - 在图像中定位模板

python - 如何从列表中检查号码而不检测具有相同数字的号码?

python - 在 __init__ 中使用 python 属性?

javascript - Django调试工具栏错误路径

python - 将两个字符串与一个公共(public)子字符串连接起来?

java - javacv中的内存泄漏

opencv - 立体三角测量的奇怪问题 : TWO valid solutions

c++ - 如何读取 OpenCV 中的像素值?