python - 查找opencv矩形的顶部和底部的y坐标

标签 python opencv computer-vision

我想将these 2个矩形合并为一个,就像this一样。我可以想到的最简单的方法是获取顶部矩形的顶部y坐标和底部矩形的底部y坐标,并在cv2.rectangle()中使用它们,但是由于for循环,我很难同时获得这两个点。

这是代码:

#Finding contours (always finds those 2 retangles + some noise):
_, conts, hierarchy = cv2.findContours(img_green, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for cnt in conts:
    area = cv2.contourArea(cnt)

    #filter all the noise
    if area > 20:

        x1, y1, w, h = cv2.boundingRect(cnt)
        x2 = x1 + w                           # (x1, y1) = top-left vertex
        y2 = y1 + h                           # (x2, y2) = bottom-right vertex
        cv2.rectangle(green_bar_win, (x1, y1), (x2, y2), (255,0,0), 2)
        print("x1:", x1, " y1:", y1, " x2:", x2, " y2:", y2)

这是打印结果(它在循环的不同迭代中打印两个矩形的左上和右下矩形点的x,y坐标):
x1: 60  y1: 217  x2: 83  y2: 288
x1: 60  y1: 169  x2: 83  y2: 216
x1: 60  y1: 217  x2: 83  y2: 288
x1: 60  y1: 169  x2: 83  y2: 216...

谢谢。

编辑:我的solution

最佳答案

除了使用坐标,您还可以通过使用“或”以更简单的方式进行操作。

如果两个矩形均为opencv类型rect,则可以简单地使用,

result = rect1 | rect2;

这将为您提供一个将两者包围的矩形。
同样,您可以执行其他操作,例如
result = rect1 & rect2;

这将为您提供两个矩形的内切面。
Reference.

关于python - 查找opencv矩形的顶部和底部的y坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48574664/

相关文章:

python - matplotlib autoscale(axis ='y') 在用 set_xlim() 分割图后

matlab - 投影矩阵符号混淆(编辑标题)

python - 从python中的HLS流中提取帧

python - 使用 python 拟合指数函数

python - (行,列)格式的 Numpy 最小值

python - Snakemake:是否可以使用目录作为通配符?

c++ - "MATLAB style"计算机视觉\图像处理可视化\调试工具

python - 当 Json 键被另一个键替换时出现 for 循环错误

c++ - OpenCV MWE 中的段错误

c++ - OpenCV和C++-形状和路标检测