OpenCV

2019-10-14

在python环境下使用opencv:

pip install opencv-python

物体检测

void detectMultiScale(
    const Mat& image,                //待检测图像
    CV_OUT vector<Rect>& objects,    //被检测物体的矩形框向量
    double scaleFactor = 1.1,        //前后两次相继的扫描中搜索窗口的比例系数,默认为1.1 即每次搜索窗口扩大10%
    int minNeighbors = 3,            //构成检测目标的相邻矩形的最小个数 如果组成检测目标的小矩形的个数和小于minneighbors - 1 都会被排除
                                     //如果minneighbors为0 则函数不做任何操作就返回所有被检候选矩形框
    int flags = 0,                   //若设置为CV_HAAR_DO_CANNY_PRUNING 函数将会使用Canny边缘检测来排除边缘过多或过少的区域 
    Size minSize = Size(),              
    Size maxSize = Size()            //最后两个参数用来限制得到的目标区域的范围     
);

对于flags,有以下取值:

CV_HAAR_DO_CANNY_PRUNING:利用Canny边缘检测器来排除一些边缘很少或者很多的图像区域;
CV_HAAR_SCALE_IMAGE:按比例正常检测;
CV_HAAR_FIND_BIGGEST_OBJECT:只检测最大的物体;
CV_HAAR_DO_ROUGH_SEARCH:只做初略检测。

摄像头实时灰度处理

import cv2

vc = cv2.VideoCapture(0)
if vc.isOpened():
    open, frame = vc.read()
else:
    open = False
    
while open:
    ret, frame = vc.read()
    if frame is None:
        break
    if ret == True:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        cv2.imshow('result',gray)
        if cv2.waitKey(10) & 0xFF == 27:
            break

vc.release()
cv2.destroyAllWindows()

人眼检测

代码

### 人眼检测
import cv2

# 创建级联分类器
classifier_eye = cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_eye.xml')
# 载入图像
img_eye = cv2.imread('a.jpg')
h,w = img_eye.shape[:2]
print(h,w)

# 利用分类器进行检测
eyeRects = classifier_eye.detectMultiScale(img_eye, 1.2, 2, cv2.CASCADE_DO_CANNY_PRUNING, (w//20, w//20))
# 检测结果
if len(eyeRects) > 0:
    for eyeRect in eyeRects:
        x, y, w, h = eyeRect
        cv2.rectangle(img_eye, (int(x), int(y)), (int(x + w), int(y + h)), (0, 255, 255), 2, 8)
cv2.imshow('eye', img_eye)
cv2.waitKey()

车牌检测

安装hyperlpr库

pip install hyperlpr

代码:

#导入包
from hyperlpr import *
#导入OpenCV库
import cv2
#读入图片
image = cv2.imread("car1.jpg")
#识别结果
res = HyperLPR_PlateRecogntion(image)
print(res[0][0])

目标追踪

安装依赖库opencv-contrib-python

pip install --user opencv-contrib-python

代码:

# 目标追踪
import cv2
import sys


print(cv2.__version__)
if __name__ == '__main__' :

    # Set up tracker.
    # Instead of MIL, you can also use

    tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN']
    tracker_type = tracker_types[2]

    
    if tracker_type == 'BOOSTING':
            tracker = cv2.TrackerBoosting_create()
    if tracker_type == 'MIL':
            tracker = cv2.TrackerMIL_create()
    if tracker_type == 'KCF':
            tracker = cv2.TrackerKCF_create()
    if tracker_type == 'TLD':
            tracker = cv2.TrackerTLD_create()
    if tracker_type == 'MEDIANFLOW':
            tracker = cv2.TrackerMedianFlow_create()
    if tracker_type == 'GOTURN':
            tracker = cv2.TrackerGOTURN_create()

    # Read video
    video = cv2.VideoCapture(0)

    # Exit if video not opened.
    if not video.isOpened():
        print("Could not open video")
        sys.exit()

    # Read first frame.
    ok, frame = video.read()
    if not ok:
        print('Cannot read video file')
        sys.exit()
    
    # Define an initial bounding box
    #bbox = (287, 23, 86, 320)

    # Uncomment the line below to select a different bounding box
    bbox = cv2.selectROI(frame, False)

    # Initialize tracker with first frame and bounding box
    ok = tracker.init(frame, bbox)

    while True:
        # Read a new frame
        ok, frame = video.read()
        if not ok:
            break
        
        # Start timer
        timer = cv2.getTickCount()

        # Update tracker
        ok, bbox = tracker.update(frame)

        # Calculate Frames per second (FPS)
        fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);

        # Draw bounding box
        if ok:
            # Tracking success
            p1 = (int(bbox[0]), int(bbox[1]))
            p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
            cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
        else :
            # Tracking failure
            cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)

        # Display tracker type on frame
        cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);
    
        # Display FPS on frame
        cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2);

        # Display result
        cv2.imshow("Tracking", frame)

        # Exit if ESC pressed
        k = cv2.waitKey(1) & 0xff
        if k == 27 : break