本文介绍了如何在opencv中合并轮廓?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我已经在这个项目上工作了一段时间了.

Ok guys I have been working on this project for quite some time now.

我正在构建一个玩铬恐龙游戏的机器人.因此,我尝试了其他方法来检测matchTemplate之类的字符,甚至制定了自己的算法来定位对象,但是我最喜欢这种方法(findcontours).

I am building this bot that plays the chrome dinosaur game. So I tried other methods to detect the characters like matchTemplate and even made my own algorithm to locate the objects, but I like this one (findcontours) the most.

这就是我所拥有的:

有人可以帮我找出如何合并仙人掌的两个矩形吗?

Can anyone help me find out how I should merge the two rectangles of the cacti?

img = screen_cap()
roi = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(roi,127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
first = True
for cnt in contours:
    area = cv2.contourArea(cnt)
    if area > 200: #filtering contours
        x,y,w,h = cv2.boundingRect(cnt)
        if w/h < 4: # filtering even more
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

推荐答案

这是一个古老的问题,似乎尚未得到正确回答(尽管对在评论中部分采用此方法的SOers表示歉意).对我来说,发问者似乎有一个分为两部分的问题:

This is an old question and seems like it has not been answered properly yet (apologies to fellow SOers who did it partially in comments though). To me it seems like the questioner has a two-part question:

  1. 是否有一个opencv函数可以合并两个矩形?

这个问题的答案是是和不是.让我清楚一点;是的,如果您使用的是opencv C ++绑定.简单与可以用来工会和|两个矩形的交点.但是Python绑定缺少这些功能.

Answer to this question is yes and no. Let me be clear; yes if you are using opencv C++ bindings. Simple & can be used to take a union and | for intersection of two rects. But Python bindings lack those functions.

  1. 然后在Python中怎么做?

  1. How to then do it in Python?

def union(a,b):
    x = min(a[0], b[0])
    y = min(a[1], b[1])
    w = max(a[0]+a[2], b[0]+b[2]) - x
    h = max(a[1]+a[3], b[1]+b[3]) - y
    return (x, y, w, h)

def intersection(a,b):
    x = max(a[0], b[0])
    y = max(a[1], b[1])
    w = min(a[0]+a[2], b[0]+b[2]) - x
    h = min(a[1]+a[3], b[1]+b[3]) - y
    if w<0 or h<0: return () # or (0,0,0,0) ?
    return (x, y, w, h)
    # Please remember a and b are rects.

源代码信用: OpenCV在rect上的联合与互动

这篇关于如何在opencv中合并轮廓?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 17:08