'str' object has no attribute 'open' in python - 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.

Related

Spyder python 3.9 AttributeError: 'NoneType' object has no attribute 'shape'

import os
import cv2
import pickle
from sklearn.cluster import KMeans
import numpy as np
train_path = './Train/'
class_list = os.listdir(train_path)
for i in range(len(class_list)):
image_list = os.listdir(os.path.join(train_path, class_list[i]))
for j in range(len(image_list)):
image = cv2.imread(os.path.join(train_path, class_list[i], image_list[j]))
sift = cv2.SIFT_create()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
(kp, descs) = sift.detectAndCompute(gray, None)
descs_samples = descs[np.random.randint(descs.shape[0], size=20)]
I am trying to get sift features of 43 diffrent classes of images but for some reason when i try to use the command descs_samples = descs[np.random.randint(descs.shape[0], size=20)] function i am getting this eror * AttributeError: 'NoneType' object has no attribute 'shape'*
My friend was able to runs this code correctly but for some reason i can't.
I tried changing my files loaction and printing images to make sure they were actullay are getting read.I was able to see my images with print (image).
My friend wasn't using the same dataset so i tought there might be something wrong with it.After a bit of debugging i found that i wasn't able to get descropitores from some of the train images.So i isolated them. I lost around %10 of the dataset but now it works great. I am trying to figure out why i couldn't get descriptores from this %10.

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

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?

Python PPTX library issue - Replacing image in slides ('SlidePart' object has no attribute 'related_parts')

I use the PPTX library to automate the creation of a deck of slides on a weekly basis.
It was working really well until the last update of the library. As you can see below, I keep getting the following when updating the "image part" of the slides:
AttributeError: 'SlidePart' object has no attribute 'related_parts'
Here is my function for the image replacement:
def replace_img_slide(prs, slide_nbr, shape_nbr, img_path):
slide = prs.slides[slide_nbr]
img = slide.shapes[shape_nbr]
try:
imgPic = img._pic
except AttributeError:
raise AttributeError(
f"Error for slide: {slide_nbr}, shape: {shape_nbr}, path: {img_path}")
imgRID = imgPic.xpath('./p:blipFill/a:blip/#r:embed')[0]
imgPart = slide.part.related_parts[imgRID]
with open(img_path, 'rb') as f:
rImgBlob = f.read()
# replace
imgPart._blob = rImgBlob
return prs
I found some related subject and I understood that the "related_parts" is now obsolete in the new version of the library but I did not find how to solve it. Do you think you can help me with that please ?
Many thanks in advance for your help !
Just use part.related_part(imgRID) where you used to use part.related_parts[imgRID].
The latest version exposes that method (internally) rather than expose a dict-like object just to do that one job.

Module not found error (imutils.paths)

This is the code i'm trying to run on an virtual environment in python3.6. I use ubuntu newest version 17.10, I run the code as python3 gather_annotations.py
import numpy as np
import cv2
import argparse
from imutils.paths import list_images
from selectors import BoxSelector
#parse arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d","--dataset",required=True,help="path to images dataset...")
ap.add_argument("-a","--annotations",required=True,help="path to save annotations...")
ap.add_argument("-i","--images",required=True,help="path to save images")
args = vars(ap.parse_args())
#annotations and image paths
annotations = []
imPaths = []
#loop through each image and collect annotations
for imagePath in list_images(args["dataset"]):
#load image and create a BoxSelector instance
image = cv2.imread(imagePath)
bs = BoxSelector(image,"Image")
cv2.imshow("Image",image)
cv2.waitKey(0)
#order the points suitable for the Object detector
pt1,pt2 = bs.roiPts
(x,y,xb,yb) = [pt1[0],pt1[1],pt2[0],pt2[1]]
annotations.append([int(x),int(y),int(xb),int(yb)])
imPaths.append(imagePath)
#save annotations and image paths to disk
annotations = np.array(annotations)
imPaths = np.array(imPaths,dtype="unicode")
np.save(args["annotations"],annotations)
np.save(args["images"],imPaths)
And I get the following errors
I have this Folder named '2' where I have all the scripts and other folder named selectors where there is 2 scripts init and box_selector
2(folder)
----selectors/
------------_ init _.py
------------box_selector.py
----detector.py
----gather_annotations.py
----test.py
----train.py
How can I fix that, in the post where I got the code from says something about 'relative imports' but i couln't fix it, thank you.
You need to use . notation to access a file inside a folder..
so
from folder.python_file import ClassOrMethod
in your case
from selectors.box_selector import BoxSelector
Having__init__.py in the selectors folder is crucial to making this work.
You can as many folders as you like and can access as follows but each folder has to contain an __init__.py to work
from folder.folder1.folder2.python_file import ClassOrMethod
One possible area of confusion is that there is a different python library called "selectors" which is DIFFERENT from the selectors of this code example.
https://docs.python.org/3/library/selectors.html
I ended up rename "selectors" (including the directory) of this example to "boxselectors"
This example is from http://www.hackevolve.com/create-your-own-object-detector/

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(),
...)

Categories

Resources