rjp*_*998 3 python opencv artificial-intelligence
好的,伙计们,我已经在这个项目上工作了很长一段时间了。
我正在构建这个玩 chrome 恐龙游戏的机器人。所以我尝试了其他方法来检测像 matchTemplate 这样的字符,甚至使用我自己的算法来定位对象,但我最喜欢这个(findcontours)。
这是我所拥有的:
谁能帮我找出我应该如何合并仙人掌的两个矩形?
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)
Run Code Online (Sandbox Code Playgroud)
小智 7
合并轮廓的最简单方法是将它们堆叠起来
contours = np.vstack(contours)
Run Code Online (Sandbox Code Playgroud)
根据您的情况(例如堆叠轮廓 5 和 6):
contours = np.vstack([contours[5], contours[6]])
Run Code Online (Sandbox Code Playgroud)
这是一个老问题,似乎还没有得到正确的回答(不过,向在评论中部分完成此问题的其他 SOers 致歉)。在我看来,提问者的问题分为两部分:
这个问题的答案是肯定和否定。让我说清楚;是的,如果您使用 opencv C++ 绑定。简单的 & 可用于取并集和 | 用于两个矩形的交集。但 Python 绑定缺少这些功能。
那么如何在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.
Run Code Online (Sandbox Code Playgroud)源代码来源:OpenCV union 和 rects 上的交互
很抱歉参加聚会迟到了一点。但是,如果我用谷歌搜索“合并 opencv 轮廓”,我会发现这个;我认为应该有一个答案。
您可以通过这些配方之一合并任何两个轮廓:
如果你不喜欢凸包的结果,因为轮廓的凹部分很重要,那么请按照以下方法进行操作:
如果两个轮廓中有很多凹形,这可能会产生锯齿形图案,因为配方会通过两个轮廓而忽略它们的原始结构。如果是这种情况,您需要遵循第三个秘诀:
下一个更复杂的情况是,如果轮廓之间有多个交叉点,并且想要保留两者之间的孔。那么最好制作一个黑色图像并通过 将轮廓绘制为白色cv2.fillPoly();然后通过cv2.findContours()
我在这里勾勒了前两个食谱的一些步骤
import cv2
list_of_pts = []
for ctr in ctrs_to_merge
list_of_pts += [pt[0] for pt in ctr]
Run Code Online (Sandbox Code Playgroud)
我使用MSeifert 这个非常棒的帖子的功能按顺时针顺序排列点
class clockwise_angle_and_distance():
'''
A class to tell if point is clockwise from origin or not.
This helps if one wants to use sorted() on a list of points.
Parameters
----------
point : ndarray or list, like [x, y]. The point "to where" we g0
self.origin : ndarray or list, like [x, y]. The center around which we go
refvec : ndarray or list, like [x, y]. The direction of reference
use:
instantiate with an origin, then call the instance during sort
reference:
/sf/ask/2929898681/
Returns
-------
angle
distance
'''
def __init__(self, origin):
self.origin = origin
def __call__(self, point, refvec = [0, 1]):
if self.origin is None:
raise NameError("clockwise sorting needs an origin. Please set origin.")
# Vector between point and the origin: v = p - o
vector = [point[0]-self.origin[0], point[1]-self.origin[1]]
# Length of vector: ||v||
lenvector = np.linalg.norm(vector[0] - vector[1])
# If length is zero there is no angle
if lenvector == 0:
return -pi, 0
# Normalize vector: v/||v||
normalized = [vector[0]/lenvector, vector[1]/lenvector]
dotprod = normalized[0]*refvec[0] + normalized[1]*refvec[1] # x1*x2 + y1*y2
diffprod = refvec[1]*normalized[0] - refvec[0]*normalized[1] # x1*y2 - y1*x2
angle = atan2(diffprod, dotprod)
# Negative angles represent counter-clockwise angles so we need to
# subtract them from 2*pi (360 degrees)
if angle < 0:
return 2*pi+angle, lenvector
# I return first the angle because that's the primary sorting criterium
# but if two vectors have the same angle then the shorter distance
# should come first.
return angle, lenvector
center_pt = np.array(list_of_pts).mean(axis = 0) # get origin
clock_ang_dist = clockwise_angle_and_distance(origin) # set origin
list_of_pts = sorted(list_of_pts, key=clock_ang_dist) # use to sort
Run Code Online (Sandbox Code Playgroud)
import numpy as np
ctr = np.array(list_of_pts).reshape((-1,1,2)).astype(np.int32)
Run Code Online (Sandbox Code Playgroud)
cv2.convexHull相反,将它们合并如果您使用它,则无需按顺时针方向对点进行排序。但是,convexHull 可能会丢失一些轮廓属性,因为它不会保留轮廓的凹角。
# get a list of points
# force the list of points into cv2 format and then
ctr = cv2.convexHull(ctr) # done.
Run Code Online (Sandbox Code Playgroud)
我认为合并两个轮廓的函数应该是opencv库的内容。这个秘诀非常简单,令人遗憾的是,许多使用 opencv 的程序员将不得不对此进行样板代码。