I applied Image deconvolution using an unsupervised wiener algorithm and increased the sharpness and contrast on a specific dataset. But I faced an error while compiling the code. It shows AttributeError: 'numpy.ndarray' object has no attribute 'convert'. How to fix it? My code is given below -
import cv2
import glob
from matplotlib import pyplot as plt
from skimage import io, color, restoration, img_as_float
import scipy.stats as st
import numpy as np
from PIL import Image
from PIL import ImageEnhance
all_img = glob.glob('input/*.png')
other_dir = 'output/'
for img_id, img_path in enumerate(all_img):
img = img_as_float(io.imread(img_path,0))
def gkern(kernlen=21, nsig=2):
lim = kernlen//2 + (kernlen % 2)/2
x = np.linspace(-lim, lim, kernlen+1)
kern1d = np.diff(st.norm.cdf(x))
kern2d = np.outer(kern1d, kern1d)
return kern2d/kern2d.sum()
psf = gkern(5,3)
deconvolved, _ = restoration.unsupervised_wiener(img, pdf)
# Applied Sharpness and contrast
enhancer_object = ImageEnhance.Contrast(deconvolved)
out = enhancer_object.enhance(1.4)
enhancer = ImageEnhance.Sharpness(out)
enhanced_im = enhancer.enhance(8.0)
enhanced_cv_im = np.array(enhanced_im)
cl2 = cv2.resize(enhanced_cv_im, (512,512), interpolation = cv2.INTER_CUBIC)
plt.imsave(f"output/unsupervised_wiener_{img_id}.png", cl2, cmap='gray')
It shows the error-
runfile('C:/Users/Junaed/.spyder-py3/unsupervised_wiener.py', wdir='C:/Users/Junaed/.spyder-py3')
Traceback (most recent call last):
File "C:\Users\Junaed\.spyder-py3\unsupervised_wiener.py", line 37, in <module>
enhancer_object = ImageEnhance.Contrast(deconvolved)
AttributeError: 'numpy.ndarray' object has no attribute 'convert'
ImageEnhance.Contrast() is expecting a PIL image which it can run image.convert on but you passed it a numpy array. To convert to PIL you can do this
from PIL import Image
import numpy
im = Image.fromarray(numpy.uint8(deconvolved))
Related
import cv2
from matplotlib import pyplot as plt
from skimage.util import random_noise
I = cv2.imread('roses.jpg', 0)
gauss = random_noise(I, mode='gaussian', seed=None, clip=True )
plt.subplot(241), plt.imshow(img), plt.title('origin')
plt.subplot(242), plt.imshow(gauss), plt.title('gaussian')
plt.show();
Detect if a signed image was input. how to fix this problem
/usr/local/lib/python3.7/dist-packages/skimage/util/noise.py in random_noise(image, mode, seed, clip, **kwargs)
if image.min() < 0:
low_clip = -1.
else:
import cv2
from matplotlib import pyplot as plt
from skimage.util import random_noise
img = cv2.imread('roses.jpg', 0)
gauss = random_noise(img, mode='gaussian', seed=None, clip=True )
plt.subplot(241), plt.imshow(img), plt.title('origin')
plt.subplot(242), plt.imshow(gauss), plt.title('gaussian')
plt.show();
if img.min() < 0:
low_clip = -1.
else:
You are saving the image as I, then using it as img, then trying to find the min of image. Your namespace is probably very cluttered and references to old things are hanging around. Be consistent and it should work if the img has a min method/attribute. If it does not, then you need to find the array that the img class represents. I suspect that opencv works like an array so the following should work:
import numpy as np
if np.min(img) < 0:
low_clip = -1.
else:
#Do something else
import numpy as np
import cv2
img = cv2.imread('home.jpg')
Z = img.reshape((-1,3))
# convert to np.float32
Z = np.float32(Z)
# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 8
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img.shape))
cv2.imshow('res2',res2)
cv2.waitKey(0)
cv2.destroyAllWindows()
Above code is simple,basic K-Means clustering code which works well for "single" image. However, I need a code for multiple images in directory.
So, I created code, but its not working with an error: 'PngImageFile' object has no attribute 'reshape' (solved problem)
But after that I have problem with error: 'numpy.ndarray' object has no attribute 'save'. I think this is because I changed code from
img = Image.open(fullpath)
#to
img = np.array(Image.open(fullpath))
Below is the code I am working on.
path = "Desktop/Gray/fmtial_gb/good_crop/"
sub_path = "Desktop/Gray/fmtial_gb/good_crop_result/"
dirs = os.listdir(path)
def kmean():
from os import listdir,makedirs
from os.path import isfile,join
import matplotlib.pylab as plt
import matplotlib.image as mpimg
import cv2
import numpy as np
from PIL import Image
import os.path, sys
for item in dirs:
fullpath = os.path.join(path,item)
pathos = os.path.join(sub_path,item)
if os.path.isfile(fullpath):
#img = Image.open(fullpath)
img = np.array(Image.open(fullpath))
f, e = os.path.splitext(pathos)
#img = cv2.imread('Desktop/Gray/fmtial_gb/good_crop/RD091090(80)Cropped.bmp')
Z = img.reshape((-1,3))
# convert to np.float32
Z = np.float32(Z)
# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 2
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img.shape))
#cv2.imshow('res2',res2)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
Image.fromarray(res2).save(f + 'kmeans.png', "png", quality=100)
kmean()
I believe it is because you are trying to reshape a PIL image object instead of a numpy array.
Try changing img = Image.open(fullpath) to img = np.array(Image.open(fullpath)) and it should work.
Here i'm trying to:
- Apply Adaptive filtering to image .
- Enhance the contrast of image .
my code is as follow :
#!/usr/bin/python
import cv2
import numpy as np
import PIL
from PIL import ImageFilter
from matplotlib import pyplot as plt
img = cv2.imread('Crop.jpg',0)
cv2.imshow('original',img)
img = cv2.medianBlur(img,5)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,11,2)
cv2.imshow('image',th3)
th3 = th3.filter(ImageFilter.SMOOTH)
cv2.imshow('image',th3)
cv2.waitKey(0)
cv2.destroyAllWindows()
I am getting following Error :
Traceback (most recent call last):
File "./adaptive.py", line 22, in
th3 = th3.filter(ImageFilter.SMOOTH)
AttributeError: 'numpy.ndarray' object has no attribute 'filter
You may confuse with cv.Smooth
I want to use ssim to compare similarity in 2 images.
I'm getting this error window_shape is incompatible with arr_in.shape .
Why? (What does it mean?)
from skimage.measure import structural_similarity as ssim
from skimage import io
img1 = io.imread('http://pasteio.com/m85cc2eed18c661bf8a0ea7e43779e742')
img2 = io.imread('http://pasteio.com/m1d45b9c70afdb576f1e3b33d342bf7d0')
ssim( img1, img2 )
Traceback (most recent call last): File "", line 1, in
File
"/var/www/wt/local/lib/python2.7/site-packages/skimage/measure/_structural_similarity.py",
line 58, in structural_similarity
XW = view_as_windows(X, (win_size, win_size)) File "/var/www/wt/local/lib/python2.7/site-packages/skimage/util/shape.py",
line 221, in view_as_windows
raise ValueError("window_shape is incompatible with arr_in.shape") ValueError: window_shape is incompatible with
arr_in.shape
I get the same error even when I feed it the same file twice ssim(img1,img1)
You need to make sure your images are the same size to compare them with scikit's ssim:
from skimage.measure import compare_ssim
from skimage.transform import resize
from scipy.ndimage import imread
import numpy as np
# resized image sizes
height = 2**10
width = 2**10
a = imread('a.jpg', flatten=True).astype(np.uint8)
b = imread('b.jpg', flatten=True).astype(np.uint8)
a = resize(a, (height, width))
b = resize(b, (height, width))
sim, diff = compare_ssim(a, b, full=True)
I have the following code:
import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
from sklearn.feature_extraction import image
from sklearn.cluster import spectral_clustering
image = cv2.imread("/home/facu/holo.tif",0)
image = image
spectrum = np.fft.fftshift(np.fft.fft2(image))
intensity = 10*np.log(np.abs(spectrum))
mask = intensity.astype(bool)
img = intensity.astype(float)
graph = image.img_to_graph(img, mask=mask)
graph.data = np.exp(-graph.data/graph.data.std())
labels = spectral_clustering(graph, k=2, mode = 'arpack')
label_img = -np.ones(mask.shape)
label_im[mask] = labels
So I'm trying to use the "spectral clustering" function but I get this error:
AttributeError: 'numpy.ndarray' object has no attribute 'img_to_graph'
How can I do for converting my "intensity" numpy array into a correct img_to_graph attribute?
You are overwriting your imported image = sklearn.feature_extraction.image with image = cv2.imread("/home/facu/holo.tif",0), so the function img_to_graph will not be accessible anymore.
The solution is to rename one of them, e.g. with
raw_img = cv2.imread("/home/facu/holo.tif",0)
and adjusting the rest accordingly.