OpenCV检测对象及其旋转

时间:2019-12-16 20:35:11

标签: python opencv image-processing

我正在一个机器人项目中,我们需要实现某种形式的图像识别以找到正确的路径。 有一个旋转的磁盘,显示如下方向:

enter image description here

我编写了以下代码,该代码使用网络摄像头成功捕获了视频流,并尝试从提供的模板中找到磁盘的图像:

import cv2

IMGn = cv2.imread("North.png",0)
webcam = cv2.VideoCapture(0)
grayScale = True
key = 0

def transformation(frame,template):
    w, h = template.shape[::-1]
    res = cv2.matchTemplate(frame,template,cv2.TM_SQDIFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    top_left = min_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)
    cv2.rectangle(frame,top_left, bottom_right, 255, 2)
    return frame

while (key!=ord('q')):
    check, frame = webcam.read()
    if(grayScale):
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    frame = transformation(frame,IMGn)

    cv2.imshow("Capturing", frame)
    key = cv2.waitKey(1)

webcam.release()
cv2.destroyAllWindows()

这不能很好地工作,但至少可以找到指南针的大致轮廓。但是我完全不确定如何找到圆的旋转!大小也似乎是一个问题(当距离太远或太近时,会弄乱跟踪)。这是我第一次对图像识别进行任何操作都没有帮助,因此请尝试简化您的答案。谢谢。

2 个答案:

答案 0 :(得分:2)

首先,您可能需要在图片上设置阈值,以便将所有灰色元素都变为白色或黑色,以便于检测。

img = cv2.imread(r"C:\Users\Max\Desktop\North_rotated_2.png")
img = cv2.resize(img, None, fx=3, fy=3)
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(imgray, (5, 5), 0)
ret, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

输出看起来像这样(我手动旋转了初始图片以使其具有一定角度)。 enter image description here

然后,我们可以检测到图像中第二大轮廓,该轮廓应该是我们的黑色半圆(最大轮廓是整个图像边界旁边的轮廓)。这是通过findContours()函数完成的:

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
areas = []

for cnt in contours:
    area = cv2.contourArea(cnt)
    areas.append((area, cnt))

areas.sort(key=lambda x: x[0], reverse=True)
areas.pop(0) # remove biggest contour
x, y, w, h = cv2.boundingRect(areas[0][1]) # get bounding rectangle around biggest contour to crop to
img = cv2.rectangle(img, (x, y), (x+w, y+h), (255,0,0), 2)
crop = thresh[y:y+h, x:x+w] # crop to size

裁剪到检测到的轮廓后,我们得到以下图像: enter image description here

最后,您可以使用HoughLines在图像中找到最长的线,该线应该是半圆的边缘。在这里,您可以找到描述rho和theta的角度,这很可能是您想知道的。如果我们以这些角度获取x,y点,然后像这样将其绘制到图像上:

edges = cv2.Canny(crop, 50, 150, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi/180, 200) # Find lines in image

img = cv2.cvtColor(crop, cv2.COLOR_GRAY2BGR) # Convert cropped black and white image to color to draw the red line
for rho, theta in lines[0]:
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))

    cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2) # draw line

然后,我们可以确保检测到正确的行,在这种情况下,这似乎不错: enter image description here

希望这可以帮助您指出正确的方向,至少可以手动将图像旋转到几个对我来说很好的位置。在[0]行中的角度应该是您在这里寻找的。

答案 1 :(得分:0)

我对cv2.findContours有问题。它似乎返回3个值,而不是2个。除此之外,代码成功检测并裁剪了图像,但在最后一步中找不到行。还有一个问题,如果图片旋转了180度以上,则由于线条旋转了180度以上,将导致错误的结果。在黑色方块内使用小的白色方块应该可以解决此问题,并根据图像向图像添加180度的偏移,但是我也不知道该怎么做。

import cv2
webcam = cv2.VideoCapture(0)

def find_disk(frame,template):
    w, h = template.shape[::-1]
    res = cv2.matchTemplate(frame,template,cv2.TM_SQDIFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    top_left = min_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)
    frame = frame[top_left[1]:bottom_right[1],top_left[0]:bottom_right[0]]
    return frame

def thresh_img(frame):
    frame = cv2.GaussianBlur(frame, (5, 5), 0)
    ret, thresh = cv2.threshold(frame, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    return thresh

def crop_disk(frame):
    _, contours, hierarchy = cv2.findContours(frame, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    areas = []
    for cnt in contours:
        area = cv2.contourArea(cnt)
        areas.append((area, cnt))

    areas.sort(key=lambda x: x[0], reverse=True)
    areas.pop(0) # remove biggest contour
    if (len(areas)>0):
        x, y, w, h = cv2.boundingRect(areas[0][1]) # get bounding rectangle around biggest contour to crop to
        crop = frame[y:y+h, x:x+w]
    else:
        crop = frame
    return crop

def find_lines(frame):
    edges = cv2.Canny(frame, 50, 150, apertureSize=3)
    lines = cv2.HoughLines(edges, 1, np.pi/180, 200)
    if (lines!=None):
        print(lines)
        img = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR) # Convert cropped black and white image to color to draw the red line
        for rho, theta in lines[0]:
            a = np.cos(theta)
            b = np.sin(theta)
            x0 = a*rho
            y0 = b*rho
            x1 = int(x0 + 1000*(-b))
            y1 = int(y0 + 1000*(a))
            x2 = int(x0 - 1000*(-b))
            y2 = int(y0 - 1000*(a))

            return cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
    else:
        return frame

key = 0

while (key!=ord('q')):
    check, frame = webcam.read()
    if(grayScale):
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    frame = find_lines(crop_disk(thresh_img(find_disk(frame,IMGn))))

    cv2.imshow("Capturing", frame)
    key = cv2.waitKey(1)
    #key = ord('q')

webcam.release()
cv2.destroyAllWindows()

这是示例输出的图片(我通过在手机上拍摄磁盘的图片并在相机前面旋转它来获得此图片)

enter image description here