天天看點

Raspberry Pi 4B 顔色檢測

  • Python:3.7.3
  • opencv-python:3.4.6.27
main.py檔案
#!/usr/bin/env python
# coding: UTF-8
#顯示攝像頭元件
import cv2
import sys, os
HSV_Configwidgets_path = os.getcwd()
sys.path.append(HSV_Configwidgets_path)
from time import time
from IPython.display import display
import HSV_Config

image = cv2.VideoCapture(0)

image.set(3, 320)
image.set(4, 240)
image.set(5, 30)  #設定幀率
image.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('M', 'J', 'P', 'G'))
image.set(cv2.CAP_PROP_BRIGHTNESS, 62) #設定亮度 -64 - 64  0.0
image.set(cv2.CAP_PROP_CONTRAST, 63) #設定對比度 -64 - 64  2.0
image.set(cv2.CAP_PROP_EXPOSURE, 4800) #設定曝光值 1.0 - 5000  156.0

update_hsv = HSV_Config.update_hsv()

color_hsv  = {"red"   : ((0, 70, 72), (7, 255, 255)),
              "green" : ((54, 109, 78), (77, 255, 255)),
              "blue"  : ((92, 100, 62), (121, 251, 255)),
              "yellow": ((26, 100, 91), (32, 255, 255))}
              
print("開始檢測...")
while True:
    start_time = time()
    ret, frame = image.read()
    frame, binary = update_hsv.get_contours(frame, color_hsv)
    parsing_time = time() - start_time
    cv2.putText(frame, "infer time(ms): %.3f, FPS: %.2f" % (parsing_time * 1000, 1 / (parsing_time + 0.0001)), (15, 55), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 255), 1)
    # 顯示檢測結果
    cv2.imshow('capture', frame)
    # 檢測按鍵
    k = cv2.waitKey(1)
    if k==27:
        break
    
image.release() 
cv2.destroyAllWindows()
      
HSV_Config.py 檔案
New script - 51cto.com.user.js:25 # !/usr/bin/env python
# coding: utf-8
import random
import cv2 as cv
import numpy as np
import tkinter as tk


class update_hsv:
    def __init__(self):
        '''
        初始化一些參數
        '''
        self.image = None
        self.binary = None

    def Image_Processing(self, hsv_range):
        '''
        形态學變換去出細小的幹擾因素
        :param img: 輸入初始圖像
        :return: 檢測的輪廓點集(坐标)
        '''
        (lowerb, upperb) = hsv_range
        # 複制原始圖像,避免處理過程中幹擾
        color_mask = self.image.copy()
        # 将圖像轉換為HSV。
        hsv_img = cv.cvtColor(self.image, cv.COLOR_BGR2HSV)
        # 篩選出位于兩個數組之間的元素。
        color = cv.inRange(hsv_img, lowerb, upperb)
        # 設定非掩碼檢測部分全為黑色
        color_mask[color == 0] = [0, 0, 0]
        # 将圖像轉為灰階圖
        gray_img = cv.cvtColor(color_mask, cv.COLOR_RGB2GRAY)
        # 擷取不同形狀的結構元素
        kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))
        # 形态學閉操作
        dst_img = cv.morphologyEx(gray_img, cv.MORPH_CLOSE, kernel)
        # 圖像二值化操作
        ret, binary = cv.threshold(dst_img, 10, 255, cv.THRESH_BINARY)
        # 擷取輪廓點集(坐标) python2和python3在此處略有不同
        # _, contours, heriachy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) #python2
        contours, heriachy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)  # python3
        return contours, binary

    def draw_contours(self, hsv_name, contours):
        '''
        采用多邊形逼近的方法繪制輪廓
        '''
        for i, cnt in enumerate(contours):
            # 計算多邊形的矩
            mm = cv.moments(cnt)
            if mm['m00'] == 0:
                continue
            cx = mm['m10'] / mm['m00']
            cy = mm['m01'] / mm['m00']
            # 擷取多邊形的中心
            (x, y) = (np.int(cx), np.int(cy))
            # 計算輪廓的⾯積
            area = cv.contourArea(cnt)
            # ⾯積⼤于10000
            if area > 800:
                # 繪制中⼼
                cv.circle(self.image, (x, y), 5, (0, 0, 255), -1)
                # 計算最小矩形區域
                rect = cv.minAreaRect(cnt)
                # 擷取盒⼦頂點
                box = cv.boxPoints(rect)
                # 轉成long類型
                box = np.int0(box)
                # 繪制最小矩形
                cv.drawContours(self.image, [box], 0, (255, 0, 0), 2)
                cv.putText(self.image, hsv_name, (int(x - 15), int(y - 15)),
                           cv.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 255), 2)

    def get_contours(self, img, color_hsv):
        binary = None
        # 規範輸入圖像大小
        self.image = cv.resize(img, (320, 240), )
        for key, value in color_hsv.items():
            # 檢測輪廓點集
            color_contours, binary = self.Image_Processing(color_hsv[key])
            # 繪制檢測圖像,并控制跟随
            self.draw_contours(key, color_contours)
        return self.image, binary