Scipy.cluster.vq.kmeans "list has no attribute shape" - python

So this is a really weird problem I've been getting. I'm basically trying to create a practice codebook which uses SIFT features of images that are clustered by the kmeans algorithm in Python. However whenever I run the code I get the following error
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\Python\assignment2\SIFT_Dectection.py", line 34, in <module>
codebook, dis = cluster.vq.kmeans(codebook_construction(files[:20]),3)
File "C:\Python27\lib\site-packages\scipy\cluster\vq.py", line 513, in kmeans
No = obs.shape[0]
AttributeError: 'list' object has no attribute 'shape'
I assume that this is an error within the vq script for the Scipy library. However, I have other friends who are working on this as well and I am using the exact same code as them with the scipy library but I'm still getting this problem. I've also tried to completely uninstall Python reinstalling everything. I'm running the thing on Windows 7 btw. The code I'm using looks something like this:
import cv2
import glob
from scipy import cluster
files = glob.glob('101_ObjectCategories/*/*.jpg')
def codebook_construction(im):
codebook = []
for image in im:
img = cv2.imread(image)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
sift = cv2.SIFT()
kp, desc = sift.detectAndCompute(gray, None)
if codebook == []:
codebook = desc
else:
codebook = np.vstack((codebook, desc))
return codebook
codebook, dis = cluster.vq.kmeans(codebook_construction(files[:20]),3)
The glob function there calls for a library of images I've downloaded from Caltech. I've searched high and low for an answer but it seems that no one has been having similar problems. Hopefully I can get some guidance here

The issue looks to be that kmeans is expecting an array, and you're feeding it a list. Try changing the last line of your codebook_construction() function to:
return scipy.array(codebook)

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 3-ValueError: not enough values to unpack (expected 3, got 2)

Hi I am a new to computer visionand stackoverflow and I have a problem with my python 3 program on Windows,as the cv2.findContours() function returns 2 instead of three values as in the documentation. I passed 2 values for return to solve the bug,the type of the first(image) is a list and that of the second (cnts)is an int32 but none of them is abled to be used in cv2.drawContours() without bugging here I use image as parameter in because it is the only list returned so I guess it is the contours list cv2.drawContours().So here is the code:
#This is the program for a document scanner so as to extract a document
#from any image and apply perspective transform to show it as final result
import numpy as np
import cv2
import imutils
from matplotlib import pyplot as plt
cap=cv2.VideoCapture(0)
ret,img=cap.read()
img1=img.copy()
cv2.imshow('Image',img1)
img1=cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
img1=cv2.bilateralFilter(img1,7,17,17)
img1=cv2.Canny(img1,30,200)
image,cnts=cv2.findContours(img1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#cnts=np.asarray(cnts,dtype='uint8')
cnts=np.array(cnts)
cv2.imshow('Edge',img1)
print('cnts var data type',cnts.dtype)
#print("Hi")
img=cv2.drawContours(img,[image],-1,(255,255,0),3)
Here is the python idle shell result appearing now:
cnts var data type is int32
Traceback (most recent call last):
File "D:\PyCharm Projects\Test_1_docscanner.py", line 20, in <module>
img=cv2.drawContours(img,[image],-1,(255,255,0),3)
TypeError: contours is not a numpy array, neither a scalar
I got it working finally,the following I did:
First I had previously messed up with most of my environmental variables haven suppressed some system variables. So I with help of a friend I retrieved as much as I could and deleted those I had stupidly ignorantly created.
Secondly I uninstalled all other python versions(at least I tried) though it seems that I still see their icons around(they seem to be "undeletable") and even the one I was using(Python3.7.3). I then install Python 3.7.4.
Thirdly,and that must be the answer is that I added this line cnts=imutils.grab_contours(cnts) before the cv2.drawContours() functions. Getting this from imutils package from Adrian Rosebrock github. my code now works because of that line which helps to parse the contours for whatever cv2.drawContours() opencv version you are using thereby avoiding conflicts of versions originating from cv2.findContours() function used prior to cv2.drawContours().
In conclusion I tried imutils.grab_contours() previously to these changes on my python3.7.3 but it did not work. But I believe above all the combination of "cnts=imutils.grab_contours(cnts)" and the update to Python3.7.4,is what solved the issue.
Hope this is helpful

any existing code/library for image sharpness or blurriness estimation in python?

I would like to find some existing code/library for sharpness/blurriness estimation on normal images. (prefer in Python) I will need to compare the performance of different algorithms later.
I have 10000+ MRI scan images with different "quality"(sharpness/blurriness). I need to write code to filter images with certain "quality"(sharpness/blurriness) which is up to user. Hence, I am trying to research about image sharpness/blurriness estimation on medical images. My supervisor told me there are lots of existing code for sharpness/blurriness estimation on normal images(maybe it is no-reference sharpness metric) on internet. She asked me to search about them and try them on normal images first. Then try to learn about their algorithms.
I have searched about this on internet and found some pages which are relevant. However, lots of them are out of date.
For example:
On
Image sharpness metric
page,
Cumulative probability of blur detection (CPBD) https://ivulab.asu.edu/software/quality/cpbd
seems not working anymore. I guess the reason is that "imread" function is removed from new "scipy" library. (please see later code and error message) I think I can try the old version of "scipy" later. However, I would like to find some more currently available code/library about image sharpness/blurriness estimation.
Also, my working environment will be in Windows 10 or CentOS-7.
I have tried the following code with CPBD:
import sys, cpbd
from scipy import ndimage
input_image1 = ndimage.imread('D:\Work\Project\scripts\test_images\blur1.png', mode='L')
input_image2 = ndimage.imread('D:\Work\Project\scripts\test_images\clr1.png', mode='L')
print("blurry image sharpness:")
cpbd.compute(input_image1)
print("clear image sharpness:")
cpbd.compute(input_image2)
Error message from Python 3.7 shell (ran in Window 10):
Traceback (most recent call last):
File "D:\Work\Project\scripts\try_cpbd.py", line 1, in <module>
import sys, cpbd
File "D:\Program_Files_2\Python\lib\site-packages\cpbd\__init__.py", line 3, in <module>
from .compute import compute
File "D:\Program_Files_2\Python\lib\site-packages\cpbd\compute.py", line 14, in <module>
from scipy.misc import imread #Original: from scipy.ndimage import imread
ImportError: cannot import name 'imread' from 'scipy.misc' (D:\Program_Files_2\Python\lib\site-packages\scipy\misc\__init__.py)
Seems that cpbd package has not been updated from some time.
It worked for me with the following steps:
Edit "D:\Program_Files_2\Python\lib\site-packages\cpbd\compute.py":
Comment the last 4 lines starting with:
#if __name__ == '__main__':
Use the python code:
import cpbd
import cv2
input_image1 = cv2.imread('blur1.png')
if input_image1 is None:
print("error opening image")
exit()
input_image1 = cv2.cvtColor(input_image1, cv2.COLOR_BGR2GRAY)
print("blurry image sharpness:")
cpbd.compute(input_image1)
Since scipy.misc.imread is deprecated since 1.0.0, and removed in 1.2.0, I would use skimage.io.imread instead (which is in most ways a drop-in replacement).
Edit the code in cpbd/compute.py
import skimage.io
input_image1 = skimage.io.imread('blur1.png')
cv2 also works (or other options: imageio, PIL, ...) but skimage tends to be a bit easier to install/use.
The following steps worked for me:
Open the compute.py from C:\ProgramData\Anaconda3\Lib\site-packages\cpbd\compute.py or wherever you have installed it. You will find the following code:
from scipy.ndimage import imread
replace it with:
from skimage.io import imread
If you can't save the compute.py file, then copy it to desktop, edit it in the above mentioned way and replace the file in C:\ProgramData\Anaconda3\Lib\site-packages\cpbd\compute.py with it.
Following the answer from Baj Mile, I did the following and it worked for me.
opened the cpbd\compute.py file
commented the line : from scipy.ndimage import imread
Added the line: import cv2
Made the following changes to the main section:
if __name__ == '__main__':
#input_image = imread(argv[1], mode='L')
input_image=cv2.imread(argv[1])
sharpness = compute(input_image)
print('CPBD sharpness for %s: %f' % (argv[1], sharpness))
close the compute.py file.
In the main code:
import cpbd
import cv2
input_image1 = cv2.imread('testimage.jpg')
input_image1 = cv2.cvtColor(input_image1, cv2.COLOR_BGR2GRAY)
cpbd.compute(input_image1)

Error in hierarchical clustering with hcluster in python

I am trying to ran the following code, and I get an AttributeError: 'module' object has no attribute 'hcluster', raised in the last line.
I am running in Mountain Lion, I use pip and homebrew, and hcluster is in PYTHONPATH=/usr/local/lib/python2.7/site-packages.
Any idea what can be going wrong? Thanks.
import os
import hcluster
from numpy import *
from PIL import Image
# create a list of images
path = 'data/flickr-sunsets-small'
imlist = [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]
# extract feature vector (8 bins per color channel)
features = zeros([len(imlist), 512])
for i,f in enumerate(imlist):
im = array(Image.open(f))
# multi-dimensional histogram
h,edges = histogramdd(im.reshape(-1,3),8,normed=True,range=[(0,255),(0,255),(0,255)])
features[i] = h.flatten()
tree = hcluster.hcluster(features)
This error means that Python cannot find the function/class hcluster in the
module hcluster, so when you do tree = hcluster.hcluster(features) it complains.
I'm not familiar with this module, but I had a quick look at this it, and it lists a function called fcluster, but no hcluster.

Categories

Resources