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 <glenn.jocher@ultralytics.com>
This commit is contained in:
RcINS 2022-03-25 20:25:30 +08:00 committed by GitHub
parent a0a4adf6de
commit d115bbf509
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 21 additions and 14 deletions

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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')