ultralytics yolo系列 detect无法正确保存中文路径

这篇博客主要讨论了在Python代码中遇到的中文路径保存导致的乱码问题。作者指出了问题发生的两个关键位置:detect.py中的cv2.imwrite函数和utils/plot.py中的save_one_box函数。为了解决这个问题,作者建议将cv2.imwrite替换为cv2.imencode,并将编码后的数据写入文件。这种方法成功解决了中文路径保存时的乱码问题。
摘要由CSDN通过智能技术生成

问题源头

detect.py 行 186 左右位置

            # Save results (image with detections)
            if save_img:
                if dataset.mode == 'image':
                    cv2.imencode('.jpg', im0)[1].tofile(save_path)
                    # cv2.imwrite(save_path, im0)

如果打开了save_crop选项,则还需修改utils/plot.py 行 458 左右位置
(这部分问题仅限老版本,新版本使用的PIL Image保存不知道会不会有这个错误)

def save_one_box(xyxy, im, file='image.jpg', gain=1.02, pad=10, square=False, BGR=False, save=True):
    # Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop
    xyxy = torch.tensor(xyxy).view(-1, 4)
    b = xyxy2xywh(xyxy)  # boxes
    if square:
        b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1)  # attempt rectangle to square
    b[:, 2:] = b[:, 2:] * gain + pad  # box wh * gain + pad
    xyxy = xywh2xyxy(b).long()
    clip_coords(xyxy, im.shape)
    crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)]
    if save:
        file.parent.mkdir(parents=True, exist_ok=True)  # make directory
        # 下一行的imencode是更改后的
        cv2.imencode('.jpg', crop)[1].tofile(str(increment_path(file).with_suffix('.jpg')))
    return crop

这两个位置里的cv2.imwrite无法正确保存中文路径,会显示乱码(第二段的cv2.imwrite已经被我修改删除了)
将这部分代码代替文件中源代码可解决保存图片和目标框时图片路径中的中文问题

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值