PythonCV2 NoneType Object - python

#!/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.

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').

How to reduce gif quality using wand?

I have the following code
from wand.image import Image
def saveSizes(f, filename):
scaled_width = 400
scaled_hight = 400
with Image() as finalImage:
with Image(filename=f) as img:
for frame in img.sequence:
#frame.transform(resize="%dx%d" % (scaled_width, scaled_hight))
frame.compression_quality = 75
finalImage.sequence.append(frame)
filename += '.gif'
finalImage.save(filename = filename)
saveSizes('source_file.gif', 'dest_file')
But the size of 'source_file.gif' is same as that of 'dest_file.gif'. Why is the "compression_quality" attribute not working?
Is there a better way to reduce the size of gif using wand or some other python lib.?
Also I am getting the following log in the console for every frame in the gif.
Exception ignored in: <bound method Resource.__del__ of <wand.sequence.SingleImage: 901eb12 (200x150)>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/wand/resource.py", line 232, in __del__
self.destroy()
File "/usr/local/lib/python3.5/site-packages/wand/sequence.py", line 331, in destroy
self.container.sequence[self.index] = self
File "/usr/local/lib/python3.5/site-packages/wand/sequence.py", line 304, in index
assert image
AssertionError:
compression_quality works fine with the source (whole file).
my working example with pdfs:
def ConvertFewPagePdfToPngs(pdf):
with wand.image.Image(filename = pdf, resolution = 200) as source:
source.compression_quality = 99
imagess = source.sequence
for i in range(len(imagess)):
imagess[i].format = 'png'
destFileName = r'path' # depends on i
wand.image.Image(imagess[i]).save(filename=destFileName)
When i tried apply compression_quality to one page i got same error as you show

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)

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

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.

CameraCalibration with Open CV

I try to calibrate a camera with python and opnecv.
I use a video-file instead of a webcam live stream.
Everything seems to work except of the last step. This is:
print "now get ready, camera is switching on"
while(1):
image=cv.QueryFrame(capture)
t = cv.CloneImage(image);
cv.ShowImage( "Calibration", image )
cv.Remap( t, image, mapx, mapy )
cv.ShowImage("Undistort", image)
c = cv.WaitKey(33)
if(c == 1048688): # enter 'p' key to pause for some time
cv.WaitKey(2000)
elif c==1048603: # enter esc key to exit
break
print "everything is fine"
There I receive following error:
Traceback (most recent call last):
File "V:\Studenten\Christian_Fuerstenhoefer\02_Kamerakalibrierung\openCV\camCalib.py", line 137, in <module>
t = cv.CloneImage(image);
TypeError: Argument 'image' must be IplImage
I already checked print type (image). Then it says None.
Does anyone know how to fix this problem?
Thanks for your help.
you don't check for the end of the stream ( each video has an end..)
while(1):
image=cv.QueryFrame(capture)
if image==None:
break

Categories

Resources