I want to improve image quality so I increase resolution, interpolate and sharpen edges with skimage and scipy. Then I want to use the threshold of the improved image for further analysis. Problem is that I get an error, when I try to pass the sharpened image array into the cv2.threshold
function.
Code:
import skimage
import scipy
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('Image.png')
scale = 5
img_rs = skimage.transform.rescale(image = img,
scale = scale,
order = 3,
mode = 'wrap',
cval = 0,
multichannel = True,
anti_aliasing = 'none')
img_int = scipy.misc.imresize(img_rs, 0.99999, interp = 'cubic')
img_int_gray = skimage.color.rgb2gray(img_int)
blurred_img = scipy.ndimage.gaussian_filter(img_int_gray, 3)
filter_blurred_img = scipy.ndimage.gaussian_filter(blurred_img, 1)
alpha = 30
sharp_img = blurred_img + alpha * (blurred_img - filter_blurred_img)
_, thresh = cv2.threshold(sharp_img,
0,
255,
cv2.THRESH_BINARY+cv2.THRESH_OTSU)
plt.imsave('sharp_img.png', sharp_img, cmap = 'gray')
Output:
Traceback (most recent call last):
File "/home/artur/Desktop/test.py", line 32, in <module>
cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.error: OpenCV(3.4.3) /io/opencv/modules/imgproc/src/thresh.cpp:1406: error: (-215:Assertion failed) src.type() == CV_8UC1 in function 'threshold'
I tried to convert the image before passing into the cv.threshold
function with:
sharp_img = skimage.img_as_ubyte(sharp_img)
Output:
Traceback (most recent call last):
File "/home/artur/Desktop/test.py", line 24, in <module>
sharp_img = skimage.img_as_ubyte(sharp_img)
File "/home/artur/.local/lib/python3.6/site-packages/skimage/util/dtype.py", line 492, in img_as_ubyte
return convert(image, np.uint8, force_copy)
File "/home/artur/.local/lib/python3.6/site-packages/skimage/util/dtype.py", line 261, in convert
raise ValueError("Images of type float must be between -1 and 1.")
ValueError: Images of type float must be between -1 and 1.
How do I make this work?
You need to ensure that the pixel values of the sharpened image are between -1 and 1. To that end you could normalize sharp_img
to the range [0, 1] before conversion to uint8
or simply use NumPy's clip like this:
sharp_img = skimage.img_as_ubyte(np.clip(sharp_img, 0, 1))