From d115bbf509aa86ed553d1dc57c078c842393cca8 Mon Sep 17 00:00:00 2001 From: RcINS Date: Fri, 25 Mar 2022 20:25:30 +0800 Subject: [PATCH] Fix `cv2.imwrite` on non-ASCII paths (#7139) * Fix imwrite on non-ASCII paths * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update general.py * Update __init__.py * Update __init__.py * Update datasets.py * Update hubconf.py * Update detect.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update general.py Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Glenn Jocher --- detect.py | 3 +-- hubconf.py | 3 ++- utils/datasets.py | 6 +----- utils/general.py | 17 ++++++++++++++++- utils/loggers/__init__.py | 6 +----- 5 files changed, 21 insertions(+), 14 deletions(-) diff --git a/detect.py b/detect.py index ccb9fbf..046f7ae 100644 --- a/detect.py +++ b/detect.py @@ -29,7 +29,6 @@ import os import sys from pathlib import Path -import cv2 import torch import torch.backends.cudnn as cudnn @@ -41,7 +40,7 @@ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative from models.common import DetectMultiBackend from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams -from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, +from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2, increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh) from utils.plots import Annotator, colors, save_one_box from utils.torch_utils import select_device, time_sync diff --git a/hubconf.py b/hubconf.py index 39fa614..d719b80 100644 --- a/hubconf.py +++ b/hubconf.py @@ -127,10 +127,11 @@ if __name__ == '__main__': # Verify inference from pathlib import Path - import cv2 import numpy as np from PIL import Image + from utils.general import cv2 + imgs = ['data/images/zidane.jpg', # filename Path('data/images/zidane.jpg'), # Path 'https://ultralytics.com/images/zidane.jpg', # URI diff --git a/utils/datasets.py b/utils/datasets.py index f212e54..d0b35e8 100755 --- a/utils/datasets.py +++ b/utils/datasets.py @@ -18,7 +18,6 @@ from threading import Thread from urllib.parse import urlparse from zipfile import ZipFile -import cv2 import numpy as np import torch import torch.nn.functional as F @@ -29,12 +28,9 @@ from tqdm import tqdm from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective from utils.general import (DATASETS_DIR, LOGGER, NUM_THREADS, check_dataset, check_requirements, check_yaml, clean_str, - segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn) + cv2, segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn) from utils.torch_utils import torch_distributed_zero_first -# Remap -cv2.imread = lambda x: cv2.imdecode(np.fromfile(x, np.uint8), cv2.IMREAD_COLOR) # for Chinese filenames - # Parameters HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data' IMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp' # include image suffixes diff --git a/utils/general.py b/utils/general.py index b0c5e9d..dcdb58c 100755 --- a/utils/general.py +++ b/utils/general.py @@ -904,5 +904,20 @@ def increment_path(path, exist_ok=False, sep='', mkdir=False): return path -# Variables +# OpenCV Chinese-friendly functions ------------------------------------------------------------------------------------ +def imread(path): + return cv2.imdecode(np.fromfile(path, np.uint8), cv2.IMREAD_COLOR) + + +def imwrite(path, im): + try: + cv2.imencode(Path(path).suffix, im)[1].tofile(path) + return True + except Exception: + return False + + +cv2.imread, cv2.imwrite = imread, imwrite # redefine + +# Variables ------------------------------------------------------------------------------------------------------------ NCOLS = 0 if is_docker() else shutil.get_terminal_size().columns # terminal window size for tqdm diff --git a/utils/loggers/__init__.py b/utils/loggers/__init__.py index ff6722e..bb8523c 100644 --- a/utils/loggers/__init__.py +++ b/utils/loggers/__init__.py @@ -11,7 +11,7 @@ import pkg_resources as pkg import torch from torch.utils.tensorboard import SummaryWriter -from utils.general import colorstr, emojis +from utils.general import colorstr, cv2, emojis from utils.loggers.wandb.wandb_utils import WandbLogger from utils.plots import plot_images, plot_results from utils.torch_utils import de_parallel @@ -147,10 +147,6 @@ class Loggers(): files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter if self.tb: - import cv2 - import numpy as np - - cv2.imread = lambda x: cv2.imdecode(np.fromfile(x, np.uint8), cv2.IMREAD_COLOR) # remap for Chinese files for f in files: self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC')