欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

目标检测图像信箱、坐标变换处理脚本

最编程 2024-10-19 17:34:18
...

import os
import shutil
from tqdm import tqdm
import cv2

def my_letter_box(img,size=(320,320)):  #
    h,w,c = img.shape
    r = min(size[0]/h,size[1]/w)
    new_h,new_w = int(h*r),int(w*r)
    top = int((size[0]-new_h)/2)
    left = int((size[1]-new_w)/2)
    
    bottom = size[0]-new_h-top
    right = size[1]-new_w-left
    img_resize = cv2.resize(img,(new_w,new_h))
    img = cv2.copyMakeBorder(img_resize,top,bottom,left,right,borderType=cv2.BORDER_CONSTANT,value=(114,114,114))
    return img,r,left,top

SRC_DIR = r"/data/detect/2/"
DST_DIR_IMG = r"/data/detect/images320/"
DST_DIR_LABELS = r"/data/detect/labels320/"

imglist = os.listdir(SRC_DIR)
for file in tqdm(imglist):
    if not file.endswith(".jpg"):
        continue

    name = file.split(".jpg")[0]
   
    if not os.path.exists(SRC_DIR+name+".txt"):
        continue
    #shutil.copy(SRC_DIR+file,DST_DIR_IMG+file)
    img =cv2.imread(SRC_DIR+file)
    h_img,w_img,c= img.shape
    img_letter,rr,left,top= my_letter_box(img)
    cv2.imwrite(DST_DIR_IMG+file,img_letter)
    with open(os.path.join(SRC_DIR, name+".txt"), 'r', encoding="utf-8") as r:
        label_list = r.readlines()

    with open(os.path.join(DST_DIR_LABELS, name+".txt"), 'a+') as ftxt:
        for label in label_list:
           
            label1 = [x for x in label.split(" ") if x != ""]
            class_name =label1[0]
            x = float(label1[1])
            y = float(label1[2])
            w = float(label1[3])
            h = float(label1[4])
            ww = w_img*w
            hh = h_img*h
            xx1 = (x-w/2)*w_img
            yy1 = (y-h/2)*h_img
            xx2 = ww+xx1
            yy2 = hh+yy1
            
            x_letter_1 = (xx1)*rr+left
            y_letter_1 = (yy1)*rr+top
            x_letter_2 = (xx2)*rr+left
            y_letter_2 = (yy2)*rr+top
            #print("x=",x)
            #print("h=",h)
            #ftxt.writelines(class_name + " " + str(xx1) + " " + str(yy1)+" " + str(xx2) + " "+str(yy2) + '\n')
            ftxt.writelines(class_name + " " + str(x_letter_1) + " " + str(y_letter_1)+" " + str(x_letter_2) + " "+str(y_letter_2) + '\n')
    ftxt.close()