AttributeError: module 'cv2' has no atrribute 'CV_CHAIN_APPROX_SIMPLE' - python

I've looked all over and can't find an answer to this question, so I am going to go ahead and ask. I am trying to figure out opencv for python and I am getting stuck. Everytime I run this code it tells me there is no attribute named 'CV_CHAIN_APPROX_SIMPLE'. Then I tried using every CV_CHAIN_APPROX and nothing worked. I even went to my IDLE and it didn't know what it was either, so I'm stuck.
I am trying to make a program that will find the center cordinates of a moving target. Would using findContours be the right direction?
Sorry! I'm new to stackoverflow, so I'm not really sure what I can ask in these questions!
Thanks so much!!
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
_, frame = cap.read()
fgmask = fgbg.apply(frame)
filtered = cv2.medianBlur(fgmask, 15)
(a, b, c) = cv2.findContours(filtered, cv2.RETR_EXTERNAL, cv2.CV_CHAIN_APPROX_SIMPLE)
cv2.imshow('cont', b)
cv2.imshow('fg', fgmask)
cv2.waitKey(1)

You are using Opencv 3.0> based on createBackgroundSubtractorMOG2, so your line need to be like:
(a, b, c) = cv2.findContours(filtered, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
Don't forget cv2. in front of every OpenCV function.

In version '2.4.9' I can clearly see cv2.CHAIN_APPROX_NONE (and others too) are you sure you haven't forgotten to add the cv2. in front of it like you did in your example. If not please add the version by doing cv2.__version__.

Related

cv2.imshow won't work after running cv.2 SelectROI

I have a problem here during cropping and saving image by using opencv.
I'm trying to crop by using cv2.SelectROI function but after I drag on the image, cv.2imshow won't work properly.
Here's my code:
import cv2, numpy as np
img = cv2.imread('C:/git/ML/Image/colorful.jpg')
x,y,w,h = cv2.selectROI('img', img, False)
if w and h:
roi = img[y:y+h, x:x+w]
cv2.imshow('cropped', roi)
cv2.moveWindow('cropped', 0, 0)
cv2.imwrite('cropped2.jpg',roi)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(x,y,w,h)
I've tried to change directory in various ways, put imshow method just before selectROI but none of them worked so far.
cv2.imshow itself shouldn't be a problem because when I don't use selectROI and just manually code the cropping performance from start to finish(by defining mouseleftbutton click, drag, leftbuttonup one by one), cv2.imshow, cv2.movewindow and cv2.imwrite works just fine.
also, not confident that the code itself have interal problem because in other computer, those activities(dragging, cropping, open in new window, save) seems to be working just fine.
is there a possibility that i haven't installed sth that should be needed in order to run selectROI..?
Anyways.. any comments will be much appreciated. Plz help me.

NoneType' object is not subscriptable

Getting the error bellow in the code
TypeError: 'NoneType' object is not subscriptable
line : crop_img = img[70:300, 70:300]
Can anyone please help me with this?
thanks a lot
img_dofh = cv2.imread("D.png",0)
ret, img = cap.read()
cv2.rectangle(img,(60,60),(300,300),(255,255,2),4) #outer most rectangle
crop_img = img[70:300, 70:300]
crop_img_2 = img[70:300, 70:300]
grey = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)
You don't show where your img variable comes from. But somehow it is None instead of containing image data.
Often this happens when you write a function that is supposed to return a valid object for img, but you forget to include a return statement in the function, so it automatically returns None instead.
Check the code that creates img.
UPDATE
Responding to your code posting:
It would be helpful if you could provide a minimal, reproducible example. That might look something like this:
import cv2
cap = cv2.VideoCapture(0)
if cap.isOpened():
ret, img = cap.read()
if img is None:
print("img was not returned.")
else:
crop_img = img[70:300, 70:300]
print(crop_img) # should show an array of image data
Looking at the documentation, it appears that your camera may not have grabbed any frames by the time you reach this point in your code. The documentation says "If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer." I would bet that the .read() function is returning a NULL pointer, which gets converted to None when it is sent back to Python.
Unfortunately, since no one else has your particular camera setup, other people may have trouble reproducing your problem.
The code above works fine on my MacBook Pro, but I have to give Terminal permission to use the camera the first time I try it. Have you tried restarting your terminal app? Does your program have access to the camera?

Weird Error in OpenCV

I'm writing a program in python using OpenCV which detects the edges (Canny Edge Detector) from the footage my webcam records. I'm also using two track-bars in order to control the threshold values (in order for to understand how these values change the output of this edge detector).
The code I wrote is the following:
import cv2
import numpy as np
def nothing(x):
pass
img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('cannyEdge')
cv2.createTrackbar("minVal", "cannyEdge", 0,100, nothing)
cv2.createTrackbar("maxVal", "cannyEdge", 100,200,nothing)
cap = cv2.VideoCapture(0)
while(True):
minVal = cv2.getTrackbarPos("minVal", "cannyEdge")
maxVal = cv2.getTrackbarPos("maxVal", "cannyEdge")
#capture frame by frame
ret, frame = cap.read()
cv2.imshow('frame', frame)
edge = cv2.Canny(frame,minVal,maxVal)
#display the resulting frame
cv2.imshow('frame', edge)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#When everything is done, release the capture
cap.release
cv2.destroyAllWindows()
This program is for educational purposes only as I'm currently learning to use OpenCV.
Every time I run the program above the code seems to be working just fine but I get the following Error:
GLib-GObject-CRITICAL **: g_object_unref: assertion 'G_IS_OBJECT (object)' failed
I've searched for the reason this error occurs but I haven't found anything helpful. My instinct tells me that my implementation for the trackbars is wrong and thus it's causing this error.
The tutorials I used are the following:
OpenCV tutorials - Canny Edge Detector
OpenCV tutorials - Trackbars
Does anybody know why this error occurs? Any help will be appreciated!
I am running Ubuntu 14.04, OpenCV 3.2.0 and Python 2.7.6
Try making the track bars and displaying the image in the same window and see if the error persists. I bet it shouldn't. Change: cv2.imshow('cannyEdge', edge)
Have you created another window named "frame"? If not, it looks like you should change 'frame' to 'cannyEdge':
cv2.imshow('cannyEdge', frame)

OpenCV Assertion Failed error: (-215) scn == 3 || scn == 4 in function cv::cvtColor works ALTERNATE times

I am a beginner in Python and OpenCV. I am trying out a piece of code which takes an input image from the webcam. The following is the piece of code.
cam = create_capture(video_src, fallback='synth:bg=../cpp/lena.jpg:noise=0.05')
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.equalizeHist(gray)
rects = detect(gray, cascade)
vis = img.copy()
draw_rects(vis, rects, (0, 255, 0))
for x1, y1, x2, y2 in rects:
roi = gray[y1:y2, x1:x2]
vis_roi = vis[y1:y2, x1:x2]
subrects = detect(roi.copy(), nested)
draw_rects(vis_roi, subrects, (255, 0, 0))
dt = clock() - t
draw_str(vis, (20, 20), 'time: %.1f ms' % (dt*1000))
cv2.imshow('facedetect', vis)
if 0xFF & cv2.waitKey(5) == 27:
break
cv2.setMouseCallback('facedetect',capture_image)
cv2.destroyAllWindows()
I am using both both Python 2.7 ans Python 3.4 to execute this. In both I face a strange problem. The code gives an assertion Error like this
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor, file ........\opencv\modules\imgproc\src\color.cpp, line 3737
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: ........\opencv\modules\imgproc\src\color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor
but it happens only on every ALTERNATE time of running. What might be the issue? I read from other posts that this error occurs when cv2.cvtColor tries to convert an empty image which does not have 3 or 4 channels. This happens usually when a wrong path is specified. For my case, since it is working fine EVERY ALTERNATE time, the source cannot be wrong. Please help!!
At least I do not find any major problem in your code, i.e. "should work". The problem seems to be in the camera driver. Cameras are different, and camera drivers are different (a.k.a. buggy).
Unfortunately, debugging the camera driver is not a very easy mission. The odd behaviour is most likely bound to the specific camera, operating system, OpenCV, and camera driver version. It is not very likely the driver can be fixed. Just try to keep everything up to date.
However, as your camera can capture every second image, there are things to do.
First, verify that the problem really is in the camera driver by replacing:
cam = create_capture(video_src, fallback='synth:bg=../cpp/lena.jpg:noise=0.05')
by
cam = create_capture('synth:bg=../cpp/lena.jpg:noise=0.05')
As is probably evident form the code, this forces the camera to be simulated. Function create_capture is only a wrapper around VideoCapture to provide this functionality. If your code runs fine with this, the problem is in the video driver.
After verifying that, you could try to run the following code:
import cv2
cam = cv2.VideoCapture(0)
cam.open(0)
results = [ cam.read()[0] for i in range(100) ]
print results
This should create a list of 100 Trues, and the process should take a few seconds, as the camera should capture 100 consecutive images.
In your code you do not seem to use the first value in the return tuple of cam.read (ret in your code). It is Trueif the image is really captured. Also, cam.read should block until there is an image available, no need to add any delays.
Most probably you will get a list [True, False, True, False, ...] because the video driver does something odd. There is no beautiful way to fix this, but there is an ugly one. Replace your capture line by:
# max. 10 retries
for i in range (10):
ret, img = cam.read()
if ret:
break
else:
# capture failed even after 10 tries
raise MyExceptiom("Video driver does not like me.")
Of course, the driver may be so broken that you have to release and reopen it once in a while. Even uglier but doable, as well.
Summary: "Most probably it cannot be cured, it does not kill you, and there are medicines to alleviate the symptoms."
Use a time.sleep(2) before entering the while loop or cap.read(). This time will help your camera to spool up.

Why does Python cv2 modules depend on (old) cv

I'm new to OpenCV and would like to use its Python binding.
When trying out the samples on OSX, I noticed
1.) The windows imshow creates are not resizable
2.) I can fix that with an prior call to cv2.namedWindow, like:
cv2.namedWindow('zoom', cv2.cv.CV_WINDOW_NORMAL)
Can we add symbols like CV_WINDOW_NORMAL from cv into cv2 !?
Who has commit rights to openCV's Python binding ?
Thanks,
Sebastian Haase
There are some omisions in the current new cv2 lib. Typically these are constants that did not get migrated to cv2 yet and are still in cv only.
Here is some code to help you find them:
import cv2
import cv2.cv as cv
nms = [(n.lower(), n) for n in dir(cv)] # list of everything in the cv module
nms2 = [(n.lower(), n) for n in dir(cv2)] # list of everything in the cv2 module
search = 'window'
print "in cv2\n ",[m[1] for m in nms2 if m[0].find(search.lower())>-1]
print "in cv\n ",[m[1] for m in nms if m[0].find(search.lower())>-1]
cv2 is a more faithful wrapper around the C++ libs than the previous cv. I found it confusing at first but it is much easier once you make the change. The code is much easier to read and numpy matrix manipulations are very fast.
I suggest you find and use the cv constants while reporting their omissions as bugs to the opencv bug tracker at willowgarage. cv2 is fresh and minty but will improve.
FYI. it is well worth instantiating the named windows before use, also killing them on exit. IMHO
E.g.
import cv2
if __name__ == '__main__':
cap = cv2.VideoCapture(0) # webcam 0
cv2.namedWindow("input")
cv2.namedWindow("grey")
key = -1
while(key < 0):
success, img = cap.read()
cv2.imshow("input", img)
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("grey", grey)
key = cv2.waitKey(1)
cv2.destroyAllWindows()

Categories

Resources