any existing code/library for image sharpness or blurriness estimation in python? - 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)

Related

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

skimage - TypeError: peak_local_max() got an unexpected keyword argument 'num_peaks_per_label'

The following code gives me the error present in the title :
from skimage.feature import peak_local_max
local_maxi = peak_local_max(imd,labels=iml,
indices=False,num_peaks_per_label=2)
Where imd is a "distance transformed image" which was obtained with :
from scipy import ndimage
imd = ndimage.distance_transform_edt(im)
im is the input binary image that I would like to later on segment with the watershed function of scikit-image. But to use this function properly, I first need to find the markers which will serve as the starting flooding points : that's what I'm trying to do with the 'peak_local_max' function.
Also, iml is the labeled version of im, that I got with :
from skimage.measure import label
iml = label(im)
I don't know what I've been doing wrong. Also, I've noticed that, the function seems to totally ignore its num_peaks argument. For instance, when I do :
local_maxi = peak_local_max(imd,labels=iml,
indices=True,num_peaks=1)
I always get the same number of peaks detected as when I set num_peaks=500 or num_peaks=np.inf. What am I missing here please ?
As #a_guest pointed out, my version of skimage wasn't matching with the version of the documentation I was referring to. The num_peaks_per_label argument is currently only available in the v0.13dev version. Updating my version to the dev version also fixed my problem with the num_peaks argument.

SPM Dicom Convert in python (Ipython/ Nipype)

I am new to python or more specifically ipython. I have been running through the steps to run what should be a very simple Dicom Conversion in a statistical package called SPM for an MRI image file as described by NiPype. I can't get it to run and was wondering what I was doing wrong. I am not getting an error message, instead, there is no file change or output. It just hangs. Does anyone have any idea what I might be doing wrong? It's likely that I am missing something very simple here (sorry :(
import os
from pylab import *
from glob import glob
from nipype.interfaces.matlab import MatlabCommand as mlab
mlab.set_default_paths('/home/orkney_01/s1252042/matlab/spm8')
from nipype.interfaces.spm.utils import DicomImport as di
os.chdir('/sdata/images/projects/ASD_MM/1/datafiles/restingstate_files')
filename = "reststate_directories.txt"
restingstate_files_list = [line.strip() for line in open(filename)]
for x in restingstate_files_list:
os.chdir( x )
y = glob('*.dcm')
conversion = di(in_files = y))
print(res.outputs)
You are creating a DicomImport interface, but you are not actually running it. You should have res = di.run().
Also, you are best to tell the interface where to run using di.base_dir = '/some/path' before running.
Finally, you may also want to print the contents of restingstate_files_list to check you are finding the DICOM directories correctly.

Error using built in gabor filters in scikit-image in Python

Iam trying to use built-in filters in python using scikit image.
However on executing this sample code,
from skimage import data, io, filters
image = data.coins() # or any NumPy array!
edges = filters.sobel(image)
io.imshow(edges)
io.show()
I get the error: " from skimage import data, io, filters
ImportError: cannot import name filters".
I have scikit image package listed in my project interpreter.How to resolve this error?

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

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)

Categories

Resources