使用tf.image.resize调整图像尺寸时保留RGB颜色遇深度不支持错误
解决tf.image.resize后OpenCV颜色转换报错问题
问题场景
原代码可正常读取并显示RGB格式图像:
img = cv2.imread('IMG_0460.jpg') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.show()
但使用tf.image.resize调整尺寸后,执行以下代码触发错误:
resize = tf.image.resize(img, (224,224)) plt.imshow(cv2.cvtColor(resize.numpy().astype(int),cv2.COLOR_BGR2RGB)) plt.show()
错误信息
--------------------------------------------------------------------------- error Traceback (most recent call last) <ipython-input-184-d6c1e44056bc> in <cell line: 2>() 1 resize = tf.image.resize(img, (224,224)) ----> 2 plt.imshow(cv2.cvtColor(resize.numpy().astype(int),cv2.COLOR_BGR2RGB)) 3 plt.show() error: OpenCV(4.7.0) /io/opencv/modules/imgproc/src/color.simd_helpers.hpp:94: error: (-2:Unspecified error) in function 'cv::impl::{anonymous}::CvtHelper<VScn, VDcn, VDepth, sizePolicy>::CvtHelper(cv::InputArray, cv::OutputArray, int) [with VScn = cv::impl::{anonymous}::Set<3, 4>; VDcn = cv::impl::{anonymous}::Set<3, 4>; VDepth = cv::impl::{anonymous}::Set<0, 2, 5>; cv::impl::{anonymous}::SizePolicy sizePolicy = cv::impl::<unnamed>::NONE; cv::InputArray = const cv::_InputArray&; cv::OutputArray = const cv::_OutputArray&]' > Unsupported depth of input image: > 'VDepth::contains(depth)' > where > 'depth' is 4 (CV_32S)
错误原因
tf.image.resize默认输出float32类型的张量- 直接用
.astype(int)会将其转为32位有符号整数(对应OpenCV的CV_32S,depth=4) - OpenCV的
cv2.cvtColor不支持该深度的图像,仅支持uint8(depth=0)、float32(depth=5)等特定类型
解决方案
方案1:转换为uint8后再用OpenCV处理
先将张量值限制在0-255范围,再转为uint8类型(符合OpenCV颜色转换要求):
import cv2 import tensorflow as tf import matplotlib.pyplot as plt img = cv2.imread('IMG_0460.jpg') resize = tf.image.resize(img, (224,224)) # 限制值范围在0-255,避免插值导致的数值溢出,再转为uint8 resized_img = tf.cast(tf.clip_by_value(resize, 0, 255), tf.uint8).numpy() plt.imshow(cv2.cvtColor(resized_img, cv2.COLOR_BGR2RGB)) plt.show()
方案2:跳过OpenCV,直接用TensorFlow调整通道顺序
利用TensorFlow反转通道实现BGR转RGB,直接传给matplotlib显示(支持float32或uint8类型):
import cv2 import tensorflow as tf import matplotlib.pyplot as plt img = cv2.imread('IMG_0460.jpg') resize = tf.image.resize(img, (224,224)) # 反转最后一维(BGR→RGB) resized_rgb = tf.reverse(resize, axis=[-1]) # float32类型需归一化到0-1范围,uint8则直接显示 plt.imshow(resized_rgb.numpy() / 255.0) plt.show() # 或者转为uint8后显示(无需归一化) resized_rgb_uint8 = tf.cast(tf.clip_by_value(resize, 0, 255), tf.uint8) resized_rgb_uint8 = tf.reverse(resized_rgb_uint8, axis=[-1]) plt.imshow(resized_rgb_uint8.numpy()) plt.show()
内容的提问来源于stack exchange,提问作者Arya Jaku
相关产品推荐
相关产品推荐

