#!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils.utils import Directory_Hanlder # Directory_Hanlder代码链接:https://blog.csdn.net/qq_16555103/article/details/107146429
import os
import time
import re
from tqdm import tqdm
import cv2
import numpy as np
import argparse
# 读取带有中文路径的图片
def cn_imread(filePath):
try:
cv_img = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), cv2.IMREAD_COLOR)
"""
cv2.imdecode 参数与 cv2.imread 打开的图片相似,如果不需要第四通道,选择 cv2.IMREAD_COLOR,此时读取图片的格式为 bgr
cv2.IMREAD_COLOR:加载彩色图片,这个是默认参数,可以直接写1。
cv2.IMREAD_GRAYSCALE:以灰度模式加载图片,可以直接写0。
cv2.IMREAD_UNCHANGED:包括alpha,可以直接写-1
"""
except Exception as e:
print('当前图片opencv无法读取,原因为:\n{}'.format(e))
cv_img = None
return cv_img
# 保存带有中文路径的图片
def cn_imwrite(file_path , img_array):
# 这个方法需要特别注意,img_array一定是一个BGR格式的uint8 ndarray
cv2.imencode('.jpg', img_array)[1].tofile(file_path)
def single_img_save(img_array,report_path,img_name):
"""
输入 img BGR格式的数组,保存图片【.jpg】到指定路径
:param img_array:
:return:
"""
img_path = os.path.join(report_path,img_name)
cn_imwrite(img_path,img_array)
# cv2.imwrite(img_path, img_array)
def single_img_intercept(fpath,top=0.0,battle=0.125):
"""
给定一张需要剪切的图片的路径 与 图片上下需要剪切的比例
:param fpath: 图片的路径
:param top: 图片上侧的比例
:param battle: 图片下侧的比例
:return:
"""
img = cn_imread(fpath)
if img is None:
return None
img_shape = img.shape
height,weight = img_shape[0],img_shape[1]
height_start = int(np.floor(top*height))
height_end = int(-1 * np.floor(battle*height))
img = img[height_start:height_end]
return img
if __name__ == '__main__':
# 创建对象
parser = argparse.ArgumentParser()
# 添加参数
parser.add_argument('--Dir', help='source dir',type=str)
parser.add_argument('--top', help='top value',type=float)
parser.add_argument('--battle', help='battle value',type=float)
# 使用parse_args解析参数
args = parser.parse_args()
dir_ = args.Dir
top = args.top
battle = args.battle
# 构建路径
source_dir = dir_
report_dir_path = os.path.join(source_dir, 'report_img')
Directory_Hanlder.check_directory(report_dir_path)
Directory_Hanlder.clean_directory(report_dir_path)
# 遍历文件夹下所有的文件
files_path, dirs_path = Directory_Hanlder.list_dir_all_files(source_dir)
# 重写图片名
for idx,img in tqdm(enumerate(files_path)):
# 将指定的文件img复制到report_dir_path的文件夹里面
img_array = single_img_intercept(img,top=top,battle=battle)
if img_array is None:
continue
img_name = img.split('\\')[-1]
# 保存
single_img_save(img_array,report_dir_path,img_name)