OpenCV汽車識別檢測數量統計

Python+OpenCV汽車識別檢測數量統計

如需遠程調試,可加QQ905733049由專業技術人員遠程協助!

運行代碼如下:

import cv2
import numpy as np
img=cv2.imread("car1.jpg")
xsize,ysize,channel=img.shape

img=cv2.resize(img,(ysize//2,xsize//2))
frame=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
mask_blue=cv2.inRange(frame,lower_blue,upper_blue)
res_blue=cv2.bitwise_and(frame,frame,mask=mask_blue)
cv2.imshow("mask_blue",mask_blue)
cv2.imshow("res_blue",res_blue)

# blur and threshold the image
blurred = cv2.blur(mask_blue, (9, 9))
(_, thresh) = cv2.threshold(blurred, 90, 255, cv2.THRESH)

"""
(_, thresh) = cv2.threshold(mask_blue, 90, 255, cv2.THRESH)
"""

# perform a series of erosions and dilations
closed = cv2.erode(closed, None, iterations=4)
closed = cv2.dilate(closed, None, iterations=4)

cv2.imshow("mask_blue2",closed)
cv2.imwrite("mask_blue2.jpg",closed)

ret, thresh = cv2.threshold(closed, 50, 250, cv2.THRESH_BINARY)
thresh_not = cv2.bitwise_not(thresh)#二值圖像的補集

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))


for i in range(550):
    F_dilation = cv2.dilate(F, kernel, iterations=1)
    F = cv2.bitwise_and(F_dilation, thresh_not)

    result = cv2.bitwise_not(F)

result,contours, hierarchy = cv2.findContours(result,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) 
cv2.drawContours(result,contours,-1,(120,0,0),2) 

count=0 
ares_avrg=0  

for cont in contours:

    ares = cv2.contourArea(cont)

    if ares<50:  
        continue
    count+=1    
    ares_avrg+=ares

    print("{}-blob:{}".format(count,ares),end="  ") 

    rect = cv2.boundingRect(cont) 
    print("x:{} y:{}".format(rect[0],rect[1]))
    x={format(rect[0])}
    y={format(rect[1])}
    print(x)
    print(y)
    y=10 if rect[1]<10 else rect[1] 
    cv2.putText(img,str(count), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2) 

print(":{}".format(round(ares_avrg/ares,2))) 

cv2.namedWindow("DetectedPhoto", 0);
cv2.imshow('DetectedPhoto',result)






運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章