2016-07-23 95 views
1

我使用OpenCV的3.1樹莓派3 I,M試圖運行下面的霍夫圓檢測算法獲得OpenCV的錯誤:斷言失敗

#! /usr/bin/python 
import numpy as np 
import cv2 
from cv2 import cv 

VInstance = cv2.VideoCapture(0) 
key = True 


""" 
params = dict(dp, 
       minDist, 
       circles, 
       param1, 
       param2, 
       minRadius, 
       maxRadius) 
""" 
def draw_circles(circles, output): 

    if circles is not None: 

     for i in circles[0,:]: 
      #draw the outer circle 
      cv2.circle(output,(i[0],i[1]),i[2],(0,255,0),2) 
      #draw the centre of the circle 
      cv2.circle(output,(i[0],i[1]),2,(0,0,255),3) 
      print("The number of circles if %d" %(circles[0].shape[0]))  
    elif circles is None: 
     print ("The number of circles is 0") 

if __name__ == '__main__': 

    while key: 
     ret,img = VInstance.read() 
     ## Smooth image to reduce the input noise 

     imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 
     imgSmooth = cv2.GaussianBlur(imgGray,(5,5),3) 

     ## Compute Hough Circles 
     circles = cv2.HoughCircles(imgSmooth,cv2.cv.CV_HOUGH_GRADIENT,1,100, 
            param1=80, 
            param2=50, 
            minRadius=50, 
            maxRadius=100) 
     draw_circles(circles,img) 

     ## Display the circles 
     cv2.imshow('detected circles',imgGray) 
     cv2.imshow("result",img) 
     k = cv2.waitKey(1) 
     if k == 27: 
      cv2.destroyAllWindows() 
      break 

但我發現了斷言失敗錯誤,詳情如下。

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp, line 8000 Traceback (most recent call last): File "HoughCircles.py", line 70, in imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.error: /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp:8000: error: (-215) scn == 3 || scn == 4 in function cvtColor

任何人都可以請檢查和幫助!

回答

1

錯誤代碼「斷言失敗(scn == 3 || scn == 4)in cvtColor」意味着您的cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)方法中的輸入(源)圖像沒有3或4個通道,這對於此類型是必需的的轉換。可能您的輸入圖像已經是灰度格式。儘量不要使用這種方法,你的問題應該得到解決。如果確實會拋出其他無法解決的錯誤或無法解決問題,請在評論中發佈您的問題。

+0

謝謝Dainius,會試着讓你知道。 –

0

這意味着輸入圖像無效,這就是爲什麼您需要檢查循環中的ret值!

的錯誤和問題的標題並沒有任何與您的霍夫圈,所以我會凝結我的答案來解決斷言失敗(加回在你的東西后面!):

#!/usr/bin/python 
import numpy as np 
import cv2 

VInstance = cv2.VideoCapture(0) 

if __name__ == '__main__': 

    while True: 
     ret,img = VInstance.read() 

     # Confirm we have a valid image returned 
     if not ret: 
      break 

     imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 

     cv2.imshow("result",img) 

     k = cv2.waitKey(1) 
     if k == 27: 
      break 

    cv2.destroyAllWindows() 
相關問題