python opencv裁剪数据增强

import glob
import random

import cv2

import numpy as np


dir=r'F:\data'

files=glob.glob(dir+'/*.jpg')


big_count=0
file_len=len(files)
for file in files:

    img_raw = cv2.imread(file)

    area_o=f"{img_raw.shape[1]*img_raw.shape[0]}_{max(img_raw.shape[1],img_raw.shape[0])}"
    if img_raw.shape[1]*img_raw.shape[0] > 200*300:
        x_scale = 224 / max(img_raw.shape[1],img_raw.shape[0])

        img_raw = cv2.resize(img_raw, None, fx=x_scale, fy=x_scale, interpolation=cv2.INTER_AREA)

    cv2.imshow("img_raw", img_raw)

    img_h,img_w=img_raw.shape[:2]

    x_1=random.randint(0, int(img_w*0.05))
    y_1=random.randint(0, int(img_h*0.05))

    x_2=random.randint( int(img_w*0.95),img_w)
    y_2=random.randint( int(img_h*0.95),img_h)
    img_crop=img_raw[y_1:y_2,x_1:x_2] #子区域

    t_h, t_w = img_crop.shape[:2]

    if t_h*t_w>50*200:
        big_count+=1

    print(file_len,big_count)
    a_w = max(t_w, t_h)
    a_w = max(a_w,200)
    img_b = np.zeros((a_w, a_w, 3), dtype=np.uint8)
    img_b[:t_h, :t_w, :] = img_crop
    img = cv2.resize(img_b,(128,128))

    cv2.imwrite(r'F:\chuli/'+area_o+".jpg",img_b)
    # cv2.imshow("img_crop", img)
    # cv2.waitKey()

猜你喜欢

转载自blog.csdn.net/jacke121/article/details/125947228
今日推荐