Opncv 实现拍照、颜色识别和阈值选取

发布时间:2023-10-07 15:00

文章目录

    • 拍照
    • 颜色识别
      • 尝试的时候一些笔记(忽略就好)
    • 获取HSV阈值
    • 鼠标点击,获取图片中点击点坐标

拍照

要先在此 .py 目录下创建picture文件夹

# created by chw 2022/3
# s 保存,q退出

import cv2


cap = cv2.VideoCapture(0)
flag = cap.isOpened()
cv2.namedWindow("Capture",cv2.WINDOW_AUTOSIZE)

if __name__ == '__main__':
    index = 1
    while flag:
        ret, frame = cap.read()
        if ret:
            cv2.imshow("Capture", frame)
            key = cv2.waitKey(1) & 0xff

            if key == ord('s'):
                print(index)
                cv2.imwrite("./picture/" + str(index) + ".jpg", frame)
                index += 1
            elif key == ord('q'):
                break

    cap.release()
    cv2.destroyAllWindows()

颜色识别

import cv2
import numpy as np

ball_color = 'green'

color_dist = {
    'red': {'Lower': np.array([0, 60, 60]), 'Upper': np.array([6, 255, 255])},
    'blue': {'Lower': np.array([100, 80, 46]), 'Upper': np.array([124, 255, 255])},
    'green': {'Lower': np.array([35, 43, 35]), 'Upper': np.array([90, 255, 255])},
}

cap = cv2.VideoCapture(0)
cv2.namedWindow('camera', cv2.WINDOW_AUTOSIZE)

while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        if frame is not None:
            gs_frame = cv2.GaussianBlur(frame, (5, 5), 0)  # 高斯模糊
            hsv = cv2.cvtColor(gs_frame, cv2.COLOR_BGR2HSV)  # 转化成 HSV 图像
            kernel = np.ones((5, 5), np.uint8)
            erode_hsv = cv2.erode(hsv, kernel, iterations=2)
            inRange_hsv = cv2.inRange(erode_hsv, color_dist[ball_color]['Lower'], color_dist[ball_color]['Upper'])
            cnts = cv2.findContours(inRange_hsv.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
            if cnts:
                c = max(cnts, key=cv2.contourArea)
                """
                    cv2.minAreaRect()
                    返回一个Box2D结构rect(最小外接矩形的中心(x, y),(宽度,高度), 旋转角度))
                    分别对应于返回值(rect[0][0],rect[0][1]),(rect[1][0],rect[1][1]),rect[2]
                """
                rect = cv2.minAreaRect(c)
                """
                    cv2.boxPoints()
                    可获取该矩形的四个顶点坐标,浮点型
                """
                box = cv2.boxPoints(rect)
                
                # 获取四个顶点坐标
                rect = np.zeros((4, 2), dtype="float32")
                # 按顺序找到对应坐标0123 分别是左上、右上、右下、左下
                # 计算左上和右下
                s = box.sum(axis=1)
                rect[0] = box[np.argmin(s)]
                rect[2] = box[np.argmax(s)]

                # 计算右上和左下
                diff = np.diff(box, axis=1)
                rect[1] = box[np.argmin(diff)]
                rect[3] = box[np.argmax(diff)]

                cv2.drawContours(frame, [np.int0(box)], -1, (0, 255, 255), 2)
                cv2.imshow('camera', frame)
                cv2.waitKey(1)
        else:
            print("无画面")
    else:
        print("无法读取摄像头!")

cap.release()
cv2.waitKey(0)
cv2.destroyAllWindows()

尝试的时候一些笔记(忽略就好)

numpy.where()的用法
一:
np.where(condition, x, y)
满足条件(condition),输出x,不满足输出y
二:
np.where(condition)
只有条件(condition),没有x和y,则输出满足条件(即非0)元素的坐标

Python中列表和数组读取一列的方法

获取HSV阈值

上面颜色识别的时候,需要知道被识别物体的HSV阈值。
当然你可以上网找,不过最适合当前环境的,当然是手动滑出来一个。

# 确定hsv颜色的最佳阈值
import cv2
import numpy as np


def nothing(x):
    pass


# 创建一个窗口图片
cv2.namedWindow('image')

# 对颜色变化创建轨迹兰
cv2.createTrackbar('HMin', 'image', 0, 179, nothing)  # Hue is from 0-179 for Opencv
cv2.createTrackbar('SMin', 'image', 0, 255, nothing)
cv2.createTrackbar('VMin', 'image', 0, 255, nothing)
cv2.createTrackbar('HMax', 'image', 0, 179, nothing)
cv2.createTrackbar('SMax', 'image', 0, 255, nothing)
cv2.createTrackbar('VMax', 'image', 0, 255, nothing)

# 设置默认HSV空间的最大值
cv2.setTrackbarPos('HMax', 'image', 179)
cv2.setTrackbarPos('SMax', 'image', 255)
cv2.setTrackbarPos('VMax', 'image', 255)

# 初始化HSV空间最大、最小值
hMin = sMin = vMin = hMax = sMax = vMax = 0
phMin = psMin = pvMin = phMax = psMax = pvMax = 0

img = cv2.imread('./picture/1.jpg')
output = img
waitTime = 33

while 1:

    # 获取轨迹栏的当前位置
    hMin = cv2.getTrackbarPos('HMin', 'image')
    sMin = cv2.getTrackbarPos('SMin', 'image')
    vMin = cv2.getTrackbarPos('VMin', 'image')

    hMax = cv2.getTrackbarPos('HMax', 'image')
    sMax = cv2.getTrackbarPos('SMax', 'image')
    vMax = cv2.getTrackbarPos('VMax', 'image')

    # 设置显示的HSV最大最小值
    lower = np.array([hMin, sMin, vMin])
    upper = np.array([hMax, sMax, vMax])

    # 创建HSV图像,并根据最低、最高阈值进行阈值化
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, lower, upper)
    output = cv2.bitwise_and(img, img, mask=mask)

    # 展示是否HSV值有变化
    if (phMin != hMin) | (psMin != sMin) | (pvMin != vMin) | (phMax != hMax) | (psMax != sMax) | (pvMax != vMax):
        print("(hMin = %d , sMin = %d, vMin = %d), (hMax = %d , sMax = %d, vMax = %d)" % (
            hMin, sMin, vMin, hMax, sMax, vMax))
        phMin = hMin
        psMin = sMin
        pvMin = vMin
        phMax = hMax
        psMax = sMax
        pvMax = vMax

    # 展示输出图像
    cv2.imshow('image', output)

    # 等待33毫秒或者按下q键退出循环
    if cv2.waitKey(waitTime) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

鼠标点击,获取图片中点击点坐标

import cv2

img = cv2.imread('./picture/1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)


def mouse_click(event, x, y, flags, para):
    if event == cv2.EVENT_LBUTTONDOWN:  # 左边鼠标点击
        print('PIX:', x, y)
        print("BGR:", img[y, x])
        print("GRAY:", gray[y, x])
        print("HSV:", hsv[y, x])


if __name__ == '__main__':
    cv2.namedWindow("img")
    cv2.setMouseCallback("img", mouse_click)
    while True:
        cv2.imshow('img', img)
        if cv2.waitKey() == ord('q'):
            break
    cv2.destroyAllWindows()

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号