Parth
Parth

Reputation: 37

Invalid index to scalar variable error in hough circles

Please check this code:

import cv2
import numpy as np
import numpy.linalg as la
import time


cap = cv2.VideoCapture("3.mp4")




fgbg = cv2.createBackgroundSubtractorMOG2()

while(True):
    _, frame = cap.read()
    if _ == False:
        print("No frame left")
        break

    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    fgmask = fgbg.apply(gray_frame)
    fgmask = cv2.resize(fgmask, (640, 360))

    gray_frame = cv2.medianBlur(fgmask, 3)
    #gray_frame = cv2.GaussianBlur(gray_frame, (3, 3), 5)
    erode_element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    dilate_element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    erosion = cv2.erode(gray_frame, erode_element, iterations = 3)
    dilation = cv2.dilate(erosion, dilate_element, iterations =  2)
    cv2.imshow("sub", dilation)
    cv2.imshow('abc', fgmask)

    rows = gray_frame.shape[0]
    circles = cv2.HoughCircles(dilation, cv2.HOUGH_GRADIENT, 1, rows / 0.01, 200, 100, 20, 10)
    print(circles)
    if circles is not None:
        for i in circles[0, :]:
            center = (i[0], i[1])
            cv2.circle(frame, center,  5, (0,0,255))

    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()

Issue is with this line:

circles = cv2.HoughCircles(dilation, cv2.HOUGH_GRADIENT, 1, rows / 0.01, 200, 100, 20, 10)

The error is:

center = (i[0], i[1])
IndexError: invalid index to scalar variable.

I cant get to know whats happening. Parameters for hough circles are taken from opencv documentation. I wanted to play around with it but cant get it to run even for a single time.

Thanks.

Upvotes: 0

Views: 363

Answers (1)

Just_Curious
Just_Curious

Reputation: 51

Just put a check for 1 dimensional np.array.

Looking at this answer just change

if circles is not None:

To

if circles is not None and circles[0][0].ndim == 1:

Upvotes: 1

Related Questions