AttributeError: 'NoneType' object has no attribute 'copy' opencv error coming when running code [duplicate] - python

This question already has answers here:
Why do I get AttributeError: 'NoneType' object has no attribute 'something'?
(11 answers)
Closed last year.
I am having an issue with this Python code:
Code And Other Things
The Error Is:
Traceback (most recent call last):
File "C:\Users\thaku\Desktop\projects\pythoncode-tutorials-master\machine-learning\face-age-prediction\predict_age.py", line 156, in <module>
predict_age(image_path)
File "C:\Users\thaku\Desktop\projects\pythoncode-tutorials-master\machine-learning\face-age-prediction\predict_age.py", line 113, in predict_age
frame = img.copy()
AttributeError: 'NoneType' object has no attribute 'copy'
I Was trying opencv as learning python. the project was to predict age but as this error came my days are wasted so please help me..
To Run The Code: python .\predict_age.py /tmp
or some new errors come

def predict_age(input_path: str):
"""Predict the age of the faces showing in the image"""
# Read Input Image
img = cv2.imread(input_path)
# Take a copy of the initial image and resize it
frame = img.copy()
Seems your error happens here because img is None, so it has no method copy() to call.
You said you are running the code like this:
.\predict_age.py /tmp
I can see that the code initialises img with the input_path which is passed as sys.argv[1]. well, /tmp is not really an image, could you try passing an image like .\predict_age.py /tmp/my_image.png

The error means that the img variable from cv2.imread(input_path) is None. I.e., something went wrong with reading the image from input_path.
In your main code, you write
import sys
image_path = sys.argv[1]
predict_age(image_path)
So the image path is given by the first argument to the program. Are you running the code as python predict_age.py 3-people.jpg?

Related

'str' object has no attribute 'open' in python

I have created a simple streamlit app which has two option one is file upload another one is capturing image
while trying to open the uploaded file i am getting an error 'str' object has no attribute 'open' .
I am not sure why the issue is occurring kindly let me know how to solve this so that i can move forward
import streamlit as st
import numpy as np
import cv2
from PIL import Image
Image = st.sidebar.selectbox(
'Choose your method',
('Upload','Capture'))
if Image == 'Upload':
uploaded_file = st.file_uploader("HI",type=['jpg','png','jpeg'])
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image,width=300)
else:
file_image = st.camera_input(label = "Take a pic of you to be sketched out")
You have here two Image keywords, one of them is the Image library you imported from PIL, and the other is the return from your selectbox, which is a string.
Since the second one is declared later, it has overridden the first one, thus giving you this error when you try to call open.
I suggest renaming the second one to anything else and it should work properly.

How to use caffe convnet for object detection in video frames?

I have use codes from this link and sucessfully done the detection but the problem is it is only from webcam. I tried to modify the code so that it can read from file. the part I have modified is : I have written this
print("[INFO] starting video stream...")
vs= cv2.VideoCapture('cars.avi')
time.sleep(2.0)
fps = FPS().start()
# loop over the frames from the video stream
while True:
# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
frame = vs.read()
instead of this (code from the above link)
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)
fps = FPS().start()
# loop over the frames from the video stream
while True:
# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
frame = vs.read()
For running the program from terminal I am using this command for both the cases:
python real_time_object_detection.py --prototxt
MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel
The error I am getting when reading from file is
the error I am getting is :
C:\Users\DEBASMITA\AppData\Local\Programs\Python\Python35\real-time-object-
detection>python videoobjectdetection.py --prototxt
MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel
[INFO] loading model...
Traceback (most recent call last):
File "videoobjectdetection.py", line 54, in <module>
frame = imutils.resize(frame, width=400)
File "C:\Users\DEBASMITA\AppData\Local\Programs\Python\Python35\lib\site-
packages\imutils\convenience.py", line 69, in resize
(h, w) = image.shape[:2]
AttributeError: 'tuple' object has no attribute 'shape'
I don't know where I am doing wrong. Please guide me.
I am unfamiliar with any of the code you are referencing, but the error is straightforward and similar errors hav been answered in other questions: You're trying to do a fancy method on a plain tuple object. Here's an example of this python concept using a common package, numpy for arrays:
#an example of the error you are getting with a plain tuple
>>>tup = (1,2,3,4)
>>>len(tup)
4
>>> tup.shape
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'shape'
#an example that uses an attribute called 'shape'
>>> import numpy as np
>>> x = np.array([1,2,3,4])
>>> x.shape
(4,)
>>> x.shape.shape
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'shape'
As you can see in my last two lines, the first time I call .shape on the numpy array, the call is valid. This call returns a tuple, so the last call to .shape.shape is invalid, it is operating on (4,). As for how to fix it? I don't know. For example, in this question the original poster thought that they were getting back some kind of image object, instead they were getting a tuple (maybe a tuple of image objects). Something similar is happening to you: Your VideoStream.read() call is returning a tuple. So when you call imutils.resize(frame, width=400) you are passing in a tuple, not an image or frame. So when that method tries to call .shape you get the error. VideoStream.read() may return a tuple by design, or an error condition. You'd have to read up on VideoStream to be sure.

Error in opencv python whie loading Video

Actually I was loading a video Using k=cv2.VideoCapture("it.mp4") which is in the same folder but when I check it is opened or not it shows "False". and when i use k.open() to open it, it shows me this error:
Traceback (most recent call last):
File "", line 1, in
TypeError: Required argument 'filename' (pos 1) not found
As I think it is not getting the file but the video is in the same folder. I am stuck on this since a long time.
Here is the code:-
import numpy as np
import cv2
cap=cv2.VideoCapture("it.mp4")
k=cap.isOpened()
if k==False:
cap.open()
And it shows the below error:-
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Required argument 'filename' (pos 1) not found
By looking at your code it is easy to figure out why you are getting this error. The reason is that you are using cap.open() without any arguments. You need to pass the filename to cap.open() in order to initialize the cv2.VideoCapture. So your code should be
import numpy as np
import cv2
cap=cv2.VideoCapture("it.mp4")
k=cap.isOpened()
if k==False:
cap.open("it.mp4")
In order to read the frames from cap you can use a loop like this
while(True):
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
You need to pass an argument for the cap.open(). In your case-
cap.open("it.mp4")
It must either be the device id in case you are using a camera or a filename which you want to read. Check out the page here.
But the actual issue here i think is that your opencv is not able to read the video you passed and which is the issue you are trying to fix. Either the file name or the extension is wrong.
If its neither, simply go to the path C:\opencv\build\x86\vc12\bin , copy the opencv_ffmpegabcd.dll and paste it in your python root directory. abcd here is your opencv version. If its a 64bit setup, copy the corresponding one.

Django - AttributeError _committed

I have a form that saves an image, and everything is working fine, but I want to be able to crop the image. However, when I used Pillow to do this, I get a strange error that doesn't really give me much to go on.
Attribute error at /userprofile/addGame/
_committed
Looking further into the traceback, the following sections were highlighted:
I'm not really sure what this error means. I think it has something to do with the form.save(committed=False), and not being able to edit files after that point, but I'm not positive. I can edit the user after that line using form.user = request.user, so I think it's the fact that I'm trying to change the image getting uploaded that is part of the issue.
This is an old post but I recently experienced a similar problem.
The information in the question is somewhat incomplete but I had the same error.
Assuming the Error being
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/Image.py", line 627, in __getattr__
raise AttributeError(name)
AttributeError: _committed
So the root problem lies with using PIL (Pillow). The function :
image = Image.open(self.cleaned_data['image'])
We wrongly assume that the object image would continue to have the
instance of image throughout the function(clean_image in my case).
So in my code structure,
def clean_image(self):
if self.cleaned_data['image']:
try:
image = Image.open(self.cleaned_data['image'])
image.verify()
except IOError:
raise forms.ValidationError(_('The file is not an image'))
return image
The error mentioned above is thrown after we execute this code. It is so because
After several of the other PIL(pillow) functions we use, we need to
open the file again. Check this out in pillow documentation
As in the code above(last line),
return image
doesn't really return anything.
To fix it
Simply add ,
image = self.cleaned_data['image']
before the return image line.
Code looks like,
except IOError:
raise forms.ValidationError(_('The file is not an image'))
image = self.cleaned_data['image']
return image
I had faced the same issue trying to save a model with an ImageFileField. My requirement was to save an image from a zip object.
Using pillow gave me the AttributeError: _committed error. Following is what worked for me:
from django.core.files.images import ImageFile
zf = zipfile.ZipFile(zip_file, mode='r')
image_list = zf.infolist()
Model.objects.create(img=ImageFile(zipObj.open(image_list[0])),
file_name=image_list[0].filename.split("/")[-1].strip(),
...)

AttributeError: 'list' object has no attribute 'updateItem'

I am working on map automation using arcpy.
I need to add a legend on the map layout based on the layers added to the mxd.I am using the code below (as given on the tutorial):
import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
lyrFile = arcpy.mapping.Layer(r"C:\Project\Data\Rivers.lyr")
arcpy.mapping.AddLayer(df, lyrFile, "TOP")
styleItem = arcpy.mapping.ListStyleItems("USER_STYLE", "Legend Items", "NewDefaultLegendStyle")[0]
legend = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT")[0]
legend.updateItem(lyrFile, styleItem)
But everytime I run this code i get the following error:
Runtime error
Traceback (most recent call last):
File "<string>", line 1, in <module>
AttributeError: 'list' object has no attribute 'updateItem'
What could cause this error to appear?
What could cause this error to appear?
Well, I am not familiar with arcpy, but it seems the 0th element of whatever ListLayoutElements() returns is a list which indeed has no updateItem() method.
You might want to .append() to the list, or you might want to have a different type of object.
Your code is the same as ArcGIS Help example,
http://resources.arcgis.com/zh-cn/help/main/10.2/index.html#//00s30000006z000000
I tested the example code and it ran correctly.
By the way, I am wondering if you had pasted your own code. Otherwise you probably encounter problem in line 2,4,6 rather than the last line.
As the user2357112 suggested, you'd better try it again with clean code. Or you can confirm the type of the variable "legend" just by print type(legend)before the line
legend.updateItem(lyrFile, styleItem)

Categories

Resources