You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TensorFlow裁剪图像后输出全黑,如何获取正确图像?

图像裁剪后全黑的解决方法

问题描述

使用以下代码裁剪图像时,保存后的图像全为黑色,无法得到正确的裁剪结果:

# Crop Image
image_open = open(fullpath, 'rb')
read_image = image_open.read()
decode = tf.image.decode_jpeg(read_image)
expand = tf.expand_dims(decode, 0)
cropped_image = tf.image.crop_and_resize(expand, boxes=[[y_min, x_min, y_max - y_min, x_max - x_min]], crop_size=[300, 300], box_indices=[0])

score = bscores[idx] * 100

file_name = OUTPUT_PATH + image_name[:-4] + '_' + str(idx) + '_' + class_label + '_' + str(round(score)) + '%' + '_' + os.path.splitext(image_name)[1]

#writefile = tf.io.write_file(file_name, encode)
tf.keras.utils.save_img(file_name, np.squeeze(cropped_image)) #I am squeezing it because it is expecting 3 dim shape 

问题原因

tf.image.crop_and_resize的boxes参数格式错误:该参数要求每个裁剪框的格式为[y_min, x_min, y_max, x_max](所有值需是归一化到0-1之间的坐标),但你写成了[y_min, x_min, y_max - y_min, x_max - x_min],把裁剪区域的高度和宽度当成了右下角坐标,导致裁剪区域超出图像范围或完全为空,最终输出全黑图像。

解决步骤

  1. 修正boxes参数格式
    将boxes改为正确的坐标格式,传入归一化后的y_min, x_min, y_max, x_max:
    # 修正后的裁剪代码
    cropped_image = tf.image.crop_and_resize(expand, boxes=[[y_min, x_min, y_max, x_max]], crop_size=[300, 300], box_indices=[0])
    
  2. 检查坐标有效性
    • 确保y_min < y_max且x_min < x_max,避免无效裁剪区域
    • 若y_min等是像素值,需先除以图像对应维度的尺寸(比如y_min = 像素值 / 图像高度),将坐标归一化到0-1之间
  3. 可选:修复数据格式问题
    若修正后仍有异常,可将张量转为uint8类型的numpy数组再保存,避免数据范围错误:
    cropped_np = np.squeeze(cropped_image.numpy()).astype(np.uint8)
    tf.keras.utils.save_img(file_name, cropped_np)
    

内容的提问来源于stack exchange,提问作者ZKS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 07:01:15