使用TensorFlow目标检测API裁剪图片遇TypeError错误求助
解决TensorFlow裁剪图片时的TypeError问题
嘿,我来帮你搞定这个报错!你遇到的TypeError: Value passed to parameter 'begin' has DataType float32 not in list of allowed values: int32, int64,核心原因是Python内置的int()函数无法正确转换TensorFlow浮点张量的类型。
你代码里用了int(yminn)这类写法,但如果yminn、xminn这些是TensorFlow输出的float32类型张量(比如从目标检测API的detection_boxes里获取的归一化坐标),int()只会把它当成Python对象处理,并不会改变张量本身的数据类型,最终传给tf.image.crop_to_bounding_box的还是float32类型的参数,这就触发了类型不匹配的错误。
正确的解决方案
把Python的int()替换成TensorFlow专门的类型转换函数tf.cast(),明确将浮点张量转为int32类型,修改后的代码如下:
cropped_image = tf.image.crop_to_bounding_box( image_np, tf.cast(yminn, tf.int32), tf.cast(xminn, tf.int32), tf.cast(ymaxx - yminn, tf.int32), tf.cast(xmaxx - xminn, tf.int32) )
额外提示(针对归一化坐标)
如果你的检测框坐标是归一化后的值(范围0-1),记得先乘以图片的实际高度和宽度,转换成绝对像素坐标后再做类型转换,否则裁剪出来的区域会完全不对:
# 获取图片的高度和宽度(TensorFlow张量形式) image_height = tf.shape(image_np)[0] image_width = tf.shape(image_np)[1] # 将归一化坐标转为绝对像素坐标 yminn = detection_boxes[0][0] * image_height xminn = detection_boxes[0][1] * image_width ymaxx = detection_boxes[0][2] * image_height xmaxx = detection_boxes[0][3] * image_width # 再进行类型转换和裁剪 cropped_image = tf.image.crop_to_bounding_box( image_np, tf.cast(yminn, tf.int32), tf.cast(xminn, tf.int32), tf.cast(ymaxx - yminn, tf.int32), tf.cast(xmaxx - xminn, tf.int32) )
这样就能满足tf.image.crop_to_bounding_box对参数类型的要求,顺利完成图片裁剪啦!
内容的提问来源于stack exchange,提问作者Ankit Satpute
相关产品推荐
相关产品推荐

