首页 > 解决方案 > 将 skimage 图像传递给 cv2.threshold 函数

问题描述

我想提高图像质量,所以我用 skimage 和 scipy 提高分辨率、插值和锐化边缘。然后我想使用改进图像的阈值进行进一步分析。问题是当我尝试将锐化的图像数组传递给cv2.threshold函数时出现错误。

图片: 在此处输入图像描述

代码:

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')

输出:

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'

我尝试在传递给cv.threshold函数之前转换图像:

sharp_img = skimage.img_as_ubyte(sharp_img)

输出:

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.

我该如何进行这项工作?

标签: pythonopencvscipyscikit-image

解决方案


您需要确保锐化图像的像素值介于 -1 和 1 之间。为此,您可以sharp_img在转换为之前标准化到 [0, 1] 范围,uint8或者像这样简单地使用 NumPy 的剪辑

sharp_img = skimage.img_as_ubyte(np.clip(sharp_img, 0, 1))

推荐阅读