![](/img/trans.png)
[英]Using haarcascade to detect licence plates with OpenCV and Python
[英]OpenCV can't get a haarcascade
我正在使用 OpenCV 庫編寫 Python 腳本。 代碼工作完美,除了一位。 我將使用 pyinstaller 構建腳本,因此我需要引用 haarcascade。
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
這行得通,但是:
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
face_cascade = cv2.CascadeClassifier(resource_path('haarcascade_frontalface_alt.xml'))
沒有。 需要幫助解決這個問題
問題是:haarcascade 不會加載,“detectMultiScale”會失敗。
相同的解決方案適用於我的另一個項目
這是我得到的錯誤: 我嘗試使用“face_cascade.load()”,它是這樣工作的:
face_cascade.load('haarcascade_frontalface_alt.xml')
但同樣不適用於“resource_path”功能
這樣做
import os.path
print(os.path.isfile(resource_path('haarcascade_frontalface_alt.xml')))
在控制台中打印“True”
我也嘗試刪除所有與檢測人臉相關的代碼,我發現 OpenCV 成功捕獲了我的網絡攝像頭
這是所有代碼:如果有人感興趣
import numpy as np
import cv2, os
cap = cv2.VideoCapture(0)
xe = 0
ye = 0
we = 0
he = 0
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
import os.path
print(os.path.isfile(resource_path('haarcascade_frontalface_alt.xml')))
face_cascade = cv2.CascadeClassifier(resource_path('haarcascade_frontalface_alt.xml'))
face_cascade.load(resource_path('haarcascade_frontalface_alt.xml'))
while 1:
ret = cap.set(3,640);
ret = cap.set(4,480);
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.2, 5)
dst = img
for (x,y,w,h) in faces:
dst = img
rows,cols,channels = img.shape
xe = x
ye = y
we = w
he = h
rows,cols,channels = img.shape
pts1 = np.float32([[xe-100,ye-100],[xe+2*we+200,ye-100],[xe-100,ye+2*he+200],[xe+2*we+200,ye+2*he+200]])
pts2 = np.float32([[0,0],[cols,0],[0,rows],[cols,rows]])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(300,300))
dst = cv2.resize(dst,(cols, rows), interpolation = cv2.INTER_CUBIC)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
編輯:
我找到了錯誤的原因:傳遞給 haarcascade 包含西里爾符號,這就是 OpenCV 加載文件時遇到困難的原因
haarcascade 文件是否真的在您期望的位置?
在您的 resource_path 函數中,您可以檢查文件是否確實存在於創建的完整路徑中以確保。
如果遇到此問題,請刪除 haarcascade 路徑中的所有西里爾符號
好吧,即使我也面臨着同樣的問題。 問題是你必須在外部提供 haarcascade 的目錄鏈接到分類器功能。
對我來說使用 anaconda 的是這個目錄:
C:\Users\lhari\anaconda3\pkgs\libopencv-3.4.2-h20b85fd_0\Library\etc\haarcascades
然后你可以加入你的路徑並像下面這樣對我有用!
path = os.path.join(r"<Your directory to the opencv package>", r"haarcascade_frontalface_default.xml")
face_classifier = cv2.CascadeClassifier(path)
我能理解的是你需要在構建exe時傳遞facecascade文件。
試試這個:
pyinstaller <filename> --add-data="<location of cascade>:.>"
通過運行此應用程序將具有級聯文件。 可以在此處找到更多詳細信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.