AttributeError: 'module' object has no attribute 'QueryFrame' - python

I am trying to test to decode a qr code real time using python and openCV 3.0.But now I am getting an error message on my terminal. I tried to search on the internet but I still unable to solve it. Can I know whats the error.
This is my Python code:
import cv2 as cv
import zbar
def scanner_procces(frame,set_zbar):
set_width = 100.0 / 100
set_height = 90.0 / 100
coord_x = int(frame.width * (1 - set_width)/2)
coord_y = int(frame.height * (1 - set_height)/2)
width = int(frame.width * set_width)
height = int(frame.height * set_height)
get_sub = cv.GetSubRect(frame, (coord_x+1, coord_y+1, width-1, height-1))
cv.Rectangle(frame, (coord_x, coord_y), (coord_x + width, coord_y + height), (255,0,0))
cm_im = cv.CreateImage((get_sub.width, get_sub.height), cv.IPL_DEPTH_8U, 1)
cv.ConvertImage(get_sub, cm_im)
image = zbar.Image(cm_im.width, cm_im.height, 'Y800', cm_im.tostring())
set_zbar.scan(image)
for symbol in image:
print '\033[1;32mResult : %s symbol "%s" \033[1;m' % (symbol.type,symbol.data)
cv.ShowImage("webcam", frame)
cv.WaitKey(10)
if __name__ == "__main__":
cv.namedWindow("webcam", cv.WINDOW_AUTOSIZE)
capture = cv.VideoCapture(0)
set_zbar = zbar.ImageScanner()
while True:
frame = cv.QueryFrame(capture)
scanner_procces(frame,set_zbar)
This is the error code:
AttributeError: 'module' object has no attribute 'QueryFrame'
This is the traceback message:
init done
opengl support available
select timeout
Traceback (most recent call last):
File "realtimetestwebcam.py", line 38, in <module>
scanner_procces(frame,set_zbar)
File "realtimetestwebcam.py", line 9, in scanner_procces
coord_x = int(frame.width * (1 - set_width)/2)
AttributeError: 'numpy.ndarray' object has no attribute 'width'
Is it the error because of the opencv version? Thank you.

When you use cv2 you should use
cv2.VideoCapture.read
instead of QueryFrame. For more info see here.
You can try this code
capture = cv.VideoCapture(0)
set_zbar = zbar.ImageScanner()
while True:
_,frame = capture.read()
Updated
This error message
AttributeError: 'numpy.ndarray' object has no attribute 'width'
you get because that changed the format of the return value. With cv frame was an object with some type, and with cv2 frame is np.ndarray. Instead of width attr you can get its dimensions with shape method. Migration from cv to cv2 is not simple process and requires rewriting of a part of the code.

I solved it by installing the python-opencv package
sudo apt-get install python-opencv
That solved my whole problem. Thanks to kvorobiev for helping me all the way.

Related

How to solve the "NameError: name 'frame' is not defined" error occured in OpenCV?

import imgaug.augmenters as iaa
import cv2
import glob
from tkinter import Frame
from tkinter import Text
from tkinter import Label
# 1. Load Dataset
images = []
images_path = glob.glob("images/*.jpg")
for img_path in images_path:
img = cv2.imread(img_path)
images.append(img)
# 2. Image Augmentation
augmentation = iaa.Sequential([
# 1. Flip
iaa.Fliplr(0.5),
iaa.Flipud(0.5),
# 2. Affine
iaa.Affine(translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)},
rotate=(-30, 30),
scale=(0.5, 1.5)),
# 3. Multiply
iaa.Multiply((0.8, 1.2)),
# 4. Linearcontrast
iaa.LinearContrast((0.6, 1.4)),
# Perform methods below only sometimes
iaa.Sometimes(0.5,
# 5. GaussianBlur
iaa.GaussianBlur((0.0, 3.0))
)
])
# 3. Show Images
counter = 0
while True:
augmented_images = augmentation(images=images)
for img in augmented_images:
counter += 1
cv2.imwrite(str(counter) + ".jpg", frame)
cv2.imwrite('Desktop/images/dog.jpg', img) # desired save location
cv2.waitKey(0)
"Traceback (most recent call last):
File "C:/Users/MC/PycharmProjects/pythonProject/Python_Augmentation.py", line 48, in
cv2.imwrite(str(counter) + ".jpg", frame)
NameError: name 'frame' is not defined"
The image augmentation code ran well, but when I tried to save the augmented images this error occurred. I also used capital 'F' instead of 'f' (frame), but I got another error.
"Traceback (most recent call last):
File "C:/Users/MC/PycharmProjects/pythonProject/Python_Augmentation.py", line 49, in
cv2.imwrite(str(counter) + ".jpg", Frame)
cv2.error: OpenCV(4.5.4-dev) :-1: error: (-5:Bad argument) in function 'imwrite'
Overload resolution failed:
img is not a numpy array, neither a scalar
Expected Ptr<cv::UMat> for argument 'img'"
Any type of help is appreciatable. Thanks in advance.
The import was:
from tkinter import Frame
but you using, in line 48: frame (lower 'f').

PythonCV2 NoneType Object

#!/usr/bin/env python
'''
Usage:
./ssearch.py input_image (f|q)
f=fast, q=quality
Use "l" to display less rects, 'm' to display more rects, "q" to quit.
'''
import sys
import cv2
if __name__ == '__main__':
# If image path and f/q is not passed as command
# line arguments, quit and display help message
if len(sys.argv) < 3:
print(__doc__)
sys.exit(1)
# speed-up using multithreads
cv2.setUseOptimized(True);
cv2.setNumThreads(4);
# read image
im = cv2.imread(sys.argv[1])
# resize image
newHeight = 200
newWidth = int(im.shape[1]*200/im.shape[0])
im = cv2.resize(im, (newWidth, newHeight))
Here i am getting error
AttributeError Traceback (most recent call last)
<ipython-input-7-b88f466ecb3b> in <module>
25 # resize image
26 newHeight = 200
---> 27 newWidth = int(im.shape[1]*200/im.shape[0])
28 im = cv2.resize(im, (newWidth, newHeight))
29
AttributeError: 'NoneType' object has no attribute 'shape'
and explain cv2.imread(sys,argv[1]) line
(2)second question is how do i get nonetype error because i havent
passed my image path from my command line yet
(3) cmd line didnt prompt because program didnt executed with th error
i am sorry i couldnt place entire code
The correct way is:
# read image
im = cv2.imread(sys.argv[1])
if im == None :
sys.exit('Invalid or missing image: ' + sys.argv[1])
BEFORE you try to do anything with your image im.

OpenCV fails on resizing

I'm using Python with OpenCV, and I'm trying to open the camera. However, I'm getting the following error:
VIDEOIO ERROR: V4L: can't open camera by index 1
VIDEOIO ERROR: V4L: can't open camera by index 0
Traceback (most recent call last):
File "set_hand_hist.py", line 71, in <module>
get_hand_hist()
File "set_hand_hist.py", line 38, in get_hand_hist
img = cv2.resize(img, (640, 480))
cv2.error: OpenCV(4.1.0) /io/opencv/modules/imgproc/src/resize.cpp:3718: error: (-215:Assertion failed) !ssize.empty() in function 'resize'
I believe that this is the corresponding part of the Python code:
def store_images(g_id):
total_pics = 1200
hist = get_hand_hist()
cam = cv2.VideoCapture(1)
if cam.read()[0]==False:
cam = cv2.VideoCapture(0)
x, y, w, h = 300, 100, 300, 300
create_folder("gestures/"+str(g_id))
pic_no = 0
flag_start_capturing = False
frames = 0
.... ... remaining code ... ...
I've tried looking on Google for a solution; however, nothing that I found yet works. I would really appreciate it if someone who is more experienced could take a look and try to help me out.
Thanks so much
Wanted to comment but I lack reputation. Seems like you can't open both cameras 1 and 0.
VIDEOIO ERROR: V4L: can't open camera by index 1
VIDEOIO ERROR: V4L: can't open camera by index 0
Please be sure a camera is connected to the system. If so, check that you have the appropriate Linux drivers installed for your camera.
And on line 38 of set_hand_hist.py, img variable is possibly an empty image. That's why you get an error on resize. You should investigate why img image is empty. Can't tell more without seeing the whole code.
Edit:You can try the code below to read images from the camera and show it. I believe the error is reading images from the camera. If the code below works, we should look elsewhere for the error.
import cv2
camera_index=1
cam = cv2.VideoCapture(1)
if not cam.read()[0]:
cam = cv2.VideoCapture(0)
camera_index=0
while True:
ret, frame = cam.read()
cv2.imshow(f"image from camera {camera_index}", frame)
if not ret:
break
k = cv2.waitKey(1)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
cam.release()
cv2.destroyAllWindows()

AttributeError: 'builtin_function_or_method' object has no attribute 'detectMultiScale'

This is the code
import cv2, sys
from numpy import array
img = cv2.imread(sys.argv[1])
img2 = array( 200 * (img[:,:,2] > img[:,:, 1]), dtype='uint8')
objects = cv2.CascadeClassifier.detectMultiScale(img2)
print (objects)
I have the error in the title at line 5. (I have tried also with cv2.CascadeClassifier.detectMultiScale(img) and I have the same error).
Many thanks!
You have to call the function detectMultiScale() on an instance of CascadeClassifier()
cascade = cv2.CascadeClassifier()
objects = cascade.detectMultiScale(img2)

Python Error in Displaying Image

On this Image
I am trying to apply:
from PIL import Image
img0 = PIL.Image.open('Entertainment.jpg')
img0 = np.float32(img0)
showarray(img0/255.0)
And I get this error:
TypeErrorTraceback (most recent call last)
<ipython-input-20-c181acf634a8> in <module>()
2 img0 = PIL.Image.open('Entertainment.jpg')
3 img0 = np.float32(img0)
----> 4 showarray(img0/255.0)
<ipython-input-8-b253b18ff9a7> in showarray(a, fmt)
11 f = BytesIO()
12 PIL.Image.fromarray(a).save(f, fmt)
---> 13 display(Image(data=f.getvalue()))
14
15 def visstd(a, s=0.1):
TypeError: 'module' object is not callable
I can't understand why.
What is not callable here?
How can I just display the image?
Image is a module that you imported
from PIL import Image
You can't call it
Image(data=f.getvalue())
There's a show method that may be useful
img0 = PIL.Image.open('Entertainment.jpg')
img0.show()
The problem may stem from how you've imported the display() function. If your import line is:
import IPython.display as display
then you need to invoke display.display() to show the image. For example:
import IPython.display as display
my_image = Image.open('something.jpg')
display.display(my_image)
If you instead invoke the function as
import IPython.display as display
my_image = Image.open('something.jpg')
display(my_image) # INCORRECT
# TypeError: 'module' object is not callable
then you will indeed get the error message in your original post because display is referring to a module, not a function.
Alternatively, if you import the display() function in the following manner, your code will work:
from IPython.display import display
my_image = Image.open('something.jpg')
display(my_image)

Categories

Resources