python+opencv通过颜色阙值识别黑色飞机,并且输出中心点

1.下载opencv-python,使用命令

pip install opencv-python=4.5.2.52

2.黑色阙值范围

lower = np.array([0,0,0])
upper = np.array([180,255,46])

3.第一种方法,识别黑色飞机直接标出中心点并且画圆
完整代码

import cv2 as cv
import numpy as np


def nothing(x):
    pass


def morphological_operation(frame):
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))  # 获取图像结构化元素
    dst = cv.morphologyEx(frame, cv.MORPH_CLOSE, kernel)  # 闭操作
    return dst


def color_detetc(frame):
    hmin1 = cv.getTrackbarPos('hmin1', 'color_adjust1')
    hmax1 = cv.getTrackbarPos('hmax1', 'color_adjust1')
    smin1 = cv.getTrackbarPos('smin1', 'color_adjust1')
    smax1 = cv.getTrackbarPos('smax1', 'color_adjust1')
    vmin1 = cv.getTrackbarPos('vmin1', 'color_adjust1')
    vmax1 = cv.getTrackbarPos('vmax1', 'color_adjust1')

    hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)  # hsv 色彩空间 分割肤色
    lower_hsv1 = np.array([hmin1, smin1, vmin1])
    upper_hsv1 = np.array([hmax1, smax1, vmax1])
    mask1 = cv.inRange(hsv, lowerb=lower_hsv1, upperb=upper_hsv1)  # hsv 掩码

    ret, thresh1 = cv.threshold(mask1, 40, 255, cv.THRESH_BINARY)  # 二值化处理

    return thresh1


def main():
    cv.namedWindow("color_adjust1")
    cv.createTrackbar("hmin1", "color_adjust1", 0, 255, nothing)
    cv.createTrackbar("hmax1", "color_adjust1", 180, 255, nothing)
    cv.createTrackbar("smin1", "color_adjust1", 0, 255, nothing)
    cv.createTrackbar("smax1", "color_adjust1", 255, 255, nothing)
    cv.createTrackbar("vmin1", "color_adjust1", 0, 255, nothing)
    cv.createTrackbar("vmax1", "color_adjust1", 46, 255, nothing)
    capture = cv.VideoCapture("2.mp4")  # 打开电脑自带摄像头,如果参数是1会打开外接摄像头
    while True:
        ret, frame = capture.read()
        mask1 = color_detetc(frame)
        scr1 = morphological_operation(mask1)
        contours1, heriachy1 = cv.findContours(scr1, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)  # 获取轮廓点集(坐标)
        cv.drawContours(frame, contours1, -1, (0, 0, 255), 2)
        for i, contour in enumerate(contours1):
            area1 = cv.contourArea(contour)
            if area1 > 500:
                print(area1)
                (x1, y1), radius1 = cv.minEnclosingCircle(contours1[i])
                x1 = int(x1)
                y1 = int(y1)
                center1 = (int(x1), int(y1))
                cv.circle(frame, center1, 3, (0, 0, 255), -1)  # 画出重心
                cv.circle(frame, center1, 100, (0, 0, 0), 3)  # 画出圆
                print("中心坐标:", (x1, y1))
                cv.putText(frame, "center:", (x1, y1), cv.FONT_HERSHEY_SIMPLEX,
                           0.5, [255, 255, 255])
        # cv.imshow("mask1", mask1)
        cv.imshow("frame", frame)
        c = cv.waitKey(50)
        if c == 27:
            break
    cv.waitKey(0)
    cv.destroyAllWindows()


if __name__ == '__main__':
    main()

4.运行截图
python+opencv通过颜色阙值识别黑色飞机,并且输出中心点_第1张图片

5.第二种方法,识别黑色飞机直接标出中心点并且画矩形
完整代码

import cv2
import numpy as np
import imutils
from imutils import contours


def main(video):
    # 颜色阈值
    lower = np.array([0, 0, 0])
    upper = np.array([180, 255, 46])
    # 内核
    kernel = np.ones((5, 5), np.uint8)
    # 打开摄像头
    vc = cv2.VideoCapture(video)
    if vc.isOpened():
        flag, frame = vc.read()
        frame = imutils.rotate(frame, 180)
        cv2.imshow("frame", frame)
    else:
        flag = False
    while flag:
        flag, frame = vc.read()
        # 翻转图像
        frame = imutils.rotate(frame, 180)
        draw_frame = frame.copy()
        if frame is None:
            break
        if flag is True:
            '''下面对摄像头读取到的图像进行处理,这个步骤是比较重要的'''
            # 转换颜色空间HSV
            frame_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
            # 颜色识别
            img = cv2.inRange(frame_hsv, lower, upper)
            # 膨胀操作
            dilation = cv2.dilate(img, kernel, iterations=1)
            # 闭操作
            closing = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, kernel)
            # 高斯滤波
            closing = cv2.GaussianBlur(closing, (5, 5), 0)
            # 边缘检测
            edges = cv2.Canny(closing, 10, 20)
            # 寻找轮廓
            cnts, _ = cv2.findContours(
                edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
            # 判断轮廓数量也就是判断是否寻找到轮廓,如果没有找到轮廓就不继续进行操作
            if len(cnts) > 0:
                # 存放轮廓面积的列表
                s = []
                # 存放最大轮廓的索引
                max_index = 0
                # 获得排序后的轮廓列表以及每个轮廓对应的外接矩形
                (cnts, boundingRects) = contours.sort_contours(cnts)
                # 寻找面积最大的轮廓的索引
                for cnt in cnts:
                    s.append(cv2.contourArea(cnt))
                max_index = s.index(max(s))
                # 根据面积最大轮廓的索引找到它的外接矩形的信息
                (x, y, w, h) = boundingRects[max_index]
                # 画矩形
                center1=(int(x + w / 2),int(y + h / 2+ 30))
                cv2.circle(draw_frame, center1, 3, (0, 0, 255), -1)  # 画出重心
                cv2.putText(draw_frame, "center:", center1, cv2.FONT_HERSHEY_SIMPLEX,
                           0.5, [255, 255, 255])
                frame_out = cv2.rectangle(
                    draw_frame, (x, y), (x + w, y + h + 60), (255, 0, 0), 2)
                print("中心坐标:", (x + w / 2, y + h / 2))
            cv2.imshow("frame", draw_frame)
            if cv2.waitKey(10) == 27:
                break
    vc.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    main("2.mp4")

6.代码运行截图
python+opencv通过颜色阙值识别黑色飞机,并且输出中心点_第2张图片
7.运行速度很快,可实时检测!!!

你可能感兴趣的:(人工智能算法,opencv,python)