python - 将 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.
我该如何进行这项工作?
解决方案
您需要确保锐化图像的像素值介于 -1 和 1 之间。为此,您可以sharp_img
在转换为之前标准化到 [0, 1] 范围,uint8
或者像这样简单地使用 NumPy 的剪辑:
sharp_img = skimage.img_as_ubyte(np.clip(sharp_img, 0, 1))
推荐阅读
- c# - 包装 HttpClient 的单元测试类
- c - 我应该改变什么,以便我的 arctan(x) 近似可以正确显示 x=1 和 x=-1?
- sql - 连接到安装在 VMware Fusion 中的 SQL Server 时出现连接错误(连接 ECONNREFUSED)
- python - 多元时间序列的 LSTM 输入形状?
- java - 分析流程工作流以便给用户一些建议
- python - 查找两个值之间的唯一数据
- java - Builder中的setService(java.lang.Class )不能应用于(java.lang.Class
) - javascript - 将上下箭头切换为图像
- javascript - IntelliJ在编写JSX时如何打开自动{}
- regex - 谷歌数据洞察中的 REGEXP_EXTRACT;继续“空”