Python中如何调整含浮点像素值的图像?OpenCV问题解析
在Python中使用OpenCV的cv2.resize()时,若输入图像为浮点类型可能触发报错,而uint类型图像可正常处理,以下是具体问题说明与解决方案:
适用于uint类型的代码示例
import numpy as np import cv2 img0 = np.array(input, dtype=np.uint) img = cv2.cvtColor(img0, cv2.COLOR_GRAY2BGR) img_resized = cv2.resize(img, new_size)
浮点类型图像触发的错误
当img0为float64类型时,OpenCV会抛出如下错误:
error: OpenCV(4.7.0)
d:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.simd_helpers.hpp:94:
error: (-2:Unspecified error) in function '__cdecl
cv::impl::anonymous-namespace'::CvtHelper<struct cv::impl::anonymous
namespace'::Set<1,-1,-1>,struct
cv::impl::A0x73cf019b::Set<3,4,-1>,struct
cv::impl::A0x73cf019b::Set<0,2,5>,2>::CvtHelper(const class
cv::_InputArray &,const class cv::_OutputArray &,int)'
Unsupported depth of input image:
'VDepth::contains(depth)'
where
'depth' is 6 (CV_64F)
解决方案
OpenCV并非完全不支持浮点像素,它支持**float32(CV_32F)**类型,但不支持float64(CV_64F)类型。只需将浮点数组转换为float32类型,即可正常使用cv2.resize()及相关OpenCV函数:
import numpy as np import cv2 # 假设input是含浮点值的数组 img0 = np.array(input, dtype=np.float32) img = cv2.cvtColor(img0, cv2.COLOR_GRAY2BGR) img_resized = cv2.resize(img, new_size)
内容的提问来源于stack exchange,提问作者Deschutes

