在CV2中使用Skimage图像

时间:2018-11-01 16:51:04

标签: python opencv matplotlib scipy scikit-image

我正在尝试使用skimage和scipy改善灰度图像的图像质量,然后在cv2中使用它们。不幸的是,当我尝试使用cv2转换skimage图像时出现错误。

图片: enter image description here

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)

#error
img_gs = cv2.cvtColor(sharp_img, cv2.COLOR_BGR2GRAY)

plt.imsave('sharp_img.png', img_gs, cmap = 'gray')

输出:

Traceback (most recent call last):
  File "/home/artur/Desktop/test.py", line 25, in <module>
    img_gs = cv2.cvtColor(sharp_img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(3.4.3) /io/opencv/modules/imgproc/src/color.hpp:255: error: (-2:Unspecified error) in function 'cv::CvtHelper<VScn, VDcn, VDepth, sizePolicy>::CvtHelper(cv::InputArray, cv::OutputArray, int) [with VScn = cv::Set<3, 4>; VDcn = cv::Set<1>; VDepth = cv::Set<0, 2, 5>; cv::SizePolicy sizePolicy = (cv::SizePolicy)2u; cv::InputArray = const cv::_InputArray&; cv::OutputArray = const cv::_OutputArray&]'
> Invalid number of channels in input image:
>     'VScn::contains(scn)'
> where
>     'scn' is 1

现在我读到skimage和cv2使用不同的格式,因此我尝试在转换为cv2之前添加此行,这应该使其与cv2兼容:

sharp_img = skimage.img_as_ubyte(sharp_img)

输出:

Traceback (most recent call last):
  File "/home/artur/Desktop/test.py", line 23, 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.

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您已经在行中将图像转换为灰度

img_int_gray = skimage.color.rgb2gray(img_int)

它在行上失败

img_gs = cv2.cvtColor(sharp_img, cv2.COLOR_BGR2GRAY)

因为它期望一个3通道的BGR图像。删除该行,您就可以用sharp_img保存plt.imsave('sharp_img.png', sharp_img, cmap = 'gray')