需求 : 使用 Python+opencv实现视频中的物体识别,
细节描述 : 用电子设备录制视屏, 对此视频进行识别,里面可能任何物品。
#!/user/bin/env python3
# -*- coding: utf-8 -*-
import cv2
# 深度学习-图像识别
def getContuors(img):
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv2.contourArea(cnt)
# print(area)
if area > 500:
cv2.drawContours(imgContour, cnt, -1, (0, 0, 0), 1)
peri = cv2.arcLength(cnt, True) # 轮廓长度
approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
objCor = len(approx)
# print(objCor)
x, y, w, h = cv2.boundingRect(approx)
if objCor == 3:
objectType = 'Tri'
elif objCor == 4:
aspRatio = w / float(h)
# print(aspRatio)
if aspRatio > 0.95 and aspRatio < 1.05:
objectType = 'ZFX'
else:
objectType = 'CFX'
elif objCor > 4:
objectType = 'YX'
else:
objectType = 'NONE'
cv2.rectangle(imgContour, (x, y), (x + w, y + h), (255, 0, 0), 1)
cv2.putText(imgContour, objectType, (x + (w // 2) - 10, y + (h // 5) - 10), cv2.FONT_HERSHEY_COMPLEX, 0.5,
(0, 0, 0), 2)
img = cv2.imread('ss.png')
imgsize = cv2.resize(img, (500, 400)) # 裁剪后
imgContour = imgsize.copy()
imgGRAY = cv2.cvtColor(imgsize, cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGRAY, (7, 7), 1) # 模糊度
imgCann = cv2.Canny(imgBlur, 50, 50)
getContuors(imgCann)
if __name__ == '__main__':
cv2.imshow('windows', imgCann)
cv2.imshow('window', imgContour)
cv2.waitKey(0)