欢迎光临散文网 会员登陆 & 注册

深深

2023-02-18 10:28 作者:变异狗熊  | 我要投稿

import CV2

import numpy as np



# 识别圆和直线

def recognize_c_l(video):

    # 获取高和宽

    height = video.shape[0]

    width = video.shape[1]

    # 转为灰度图

    gray_img = CV2.cvtColor(video, CV2.COLOR_BGRA2GRAY)

    # 进行中值模糊,去噪点

    img = CV2.medianBlur(gray_img, 7)


    # 霍夫圆检测

    circles = CV2.HoughCircles(img, CV2.HOUGH_GRADIENT, 1, 50, param1=100, param2=75, minRadius=0, maxRadius=0)

    # 在检测到圆的情况下输出圆坐标,并画圆

    if circles is not None:

        circles = np.uint16(np.around(circles))

        # print(circles)

        for i in circles[0, :]:  # 遍历矩阵每一行的数据

            CV2.circle(video, (i[0], i[1]), i[2], (0, 255, 0), 2)

            CV2.circle(video, (i[0], i[1]), 2, (0, 0, 255), 3)

            # 偏离坐标显示

            h = int(height / 2 - i[1])

            w = int(i[0] - width / 2)

            # print("(%d,%d)" % (w, h))

            # 坐标显示

            str1 = '(' + str(w) + ',' + str(h) + ')'

            CV2.putText(video, str1, (int(i[0]) - 50, int(i[1]) + 40), CV2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2,

                        CV2.LINE_AA)

    # canny边缘检测

    canny = CV2.Canny(gray_img, 30, 150)

    # 霍夫直线检测

    lines = CV2.HoughLines(canny, 1, np.pi / 180, 200)

    if lines is not None:

        lines1 = lines[:, 0, :]

        for rho, theta in lines1[:]:

            a = np.cos(theta)

            b = np.sin(theta)

            x0 = a * rho

            y0 = b * rho

            x1 = int(x0 + 3000 * (-b))

            y1 = int(y0 + 3000 * (a))

            x2 = int(x0 - 3000 * (-b))

            y2 = int(y0 - 3000 * (a))

            CV2.line(video, (x1, y1), (x2, y2), (0, 0, 255), 2)

    return video



# 识别色块

def recognize_color(target_color, img):

    height = img.shape[0]

    width = img.shape[1]

    # 高斯模糊

    gs_frame = CV2.GaussianBlur(img, (5, 5), 0)

    # HSV转化

    hsv = CV2.cvtColor(gs_frame, CV2.COLOR_BGR2HSV)

    erode_hsv = CV2.erode(hsv, None, iterations=2)

    for i in target_color:

        mask = CV2.inRange(erode_hsv, color_dist[i]['Lower'], color_dist[i]['Upper'])

        if i == target_color[0]:

            inRange_hsv = CV2.bitwise_and(erode_hsv, erode_hsv, mask=mask)

        else:

            inRange_hsv1 = CV2.bitwise_and(erode_hsv, erode_hsv, mask=mask)

            inRange_hsv = CV2.add(inRange_hsv, inRange_hsv1)

    inRange_gray = CV2.cvtColor(inRange_hsv, CV2.COLOR_BGR2GRAY)

    contours, hierarchy = CV2.findContours(inRange_gray, CV2.RETR_TREE, CV2.CHAIN_APPROX_NONE)

    for c in contours:

        if CV2.contourArea(c) < 2000:  # 过滤掉较面积小的物体

            continue

        else:

            target_list.append(c)  # 将面积较大的物体视为目标并存入目标列表

    # for i in target_list:  # 绘制目标外接矩形

    # rect = CV2.minAreaRect(i)

    # box = CV2.boxPoints(rect)

    # CV2.drawContours(draw_img, [np.int0(box)], -1, (0, 255, 255), 2)

    for c in target_list:

        # 找坐标

        M = CV2.moments(c)

        center_x = int(M['m10'] / M['m00'])

        center_y = int(M['m01'] / M['m00'])

        # print('center_x:', center_x)

        # print('center_y:', center_y)

        # 绘制中心点

        CV2.circle(img, (center_x, center_y), 7, 128, -1)

        h = int(height / 2 - center_y)

        w = int(center_x - width / 2)

        str1 = '(' + str(w) + ',' + str(h) + ')'

        CV2.putText(img, str1, (center_x - 50, center_y + 40), CV2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2,

                    CV2.LINE_AA)

    return img



# 颜色列表

color_dist = {'red': {'Lower': np.array([156, 128, 46]), 'Upper': np.array([180, 255, 255])},

              'yellow': {'Lower': np.array([15, 160, 50]), 'Upper': np.array([35, 255, 255])},

              'green': {'Lower': np.array([35, 43, 35]), 'Upper': np.array([90, 255, 255])},

              'blue': {'Lower': np.array([80, 80, 150]), 'Upper': np.array([110, 255, 255])},

              }

# 目标颜色(待识别)

target_color = ['blue']


# 调用摄像头

cap = CV2.VideoCapture(0)

while cap.isOpened():

    target_list = []

    # 逐帧捕获

    ret, frame = cap.read()


    # 展示捕获的原图像

    # CV2.imshow("capture", frame)

    # CV2.waitKey(1)


    # 展示处理图

    process_1 = recognize_color(target_color, frame)

    process_2 = recognize_c_l(process_1)

    CV2.imshow("process", process_2)

    # 按Esc退出

    if CV2.waitKey(30) & 0xff == 27:

        break

    # 一切完成后,释放捕获

cap.release()

CV2.destroyAllWindows()


深深的评论 (共 条)

分享到微博请遵守国家法律