Zvonko Bednarcik
Zvonko Bednarcik

Reputation: 25

Python OpenCV: inRange() stopped working without change

I am currently doing real time object detection of an orange ball with Raspberry Pi 3 Model B. The code below is supposed to take a frame, then with the cv2.inRange() function, filter out the image using RGB (BGR). Then I apply dialation and erosion to remove noise. Then I find the contours and draw them. This code worked until now. However when I ran it today without changing it, I got the folowing error:

 Traceback (most recent call last):
 File "/home/pi/Desktop/maincode.py", line 12, in <module>
   mask = cv2.inRange(frame, lower, upper)
error: /build/opencv-ISmtkH/opencv-2.4.9.1+dfsg/modules/core/src/arithm.cpp:2701: error: (-209) The lower bounary is neither an array of the same size and same type as src, nor a scalar in function inRange

Any help would be really awesome, because I was new to openCV and spent a lot of time proggraming this, and I have a competetion of robotics in 5 days.

Thank you in advance

            import cv2
            import cv2.cv as cv
            import numpy as np


            capture = cv2.VideoCapture(0)
            while capture.isOpened:
                    ret, frame = capture.read()
                    im = frame
                    lower = np.array([0, 100 ,150], dtype = 'uint8')
                    upper = np.array([10,180,255], dtype = 'uint8')
                    mask = cv2.inRange(frame, lower, upper)
                    eroded = cv2.erode(mask, np.ones((7, 7)))
                    dilated = cv2.dilate(eroded, np.ones((7, 7)))
                    contours, hierarchy =   cv2.findContours(dilated,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

                    cv2.drawContours(im,contours,-1,(0,255,0),3)
                    cv2.imshow('colors',im)
                    cv2.waitKey(1)

Upvotes: 1

Views: 1400

Answers (1)

Jurjen
Jurjen

Reputation: 1396

The error you receive almost certainly means you have an empty image (or you mix up the sizes of your input image).

Webcam captures in OpenCV often start with one or a couple of black/emtpy images (crappy drivers). Since it goes too fast, that's why you don't notice this. However, this will have an influence on your application if you want to process the image. Therefore, I recommend you to check the image before proceeding with the calculations on them. Just add this after your capture.read() line:

if ret == True:

Note: make sure (by printing in the console or something) that this only happens when you start capturing. If this happens regularly (empty frames from your webcam), maybe there's something else wrong (or maybe with your webcam). Also check it on another computer.

Upvotes: 2

Related Questions