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

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()

相关推荐
Gloria_niki9 分钟前
目标检测学习总结
人工智能·计算机视觉·目标跟踪
Juchecar1 小时前
给AI装上“手脚”:大模型如何自动执行复杂任务?
人工智能
长鸳词羡1 小时前
LoRA微调
人工智能·深度学习·机器学习
jerryinwuhan1 小时前
Transformer ViT 架构(转载)
人工智能·深度学习·transformer
码农阿豪1 小时前
【征文计划】码上分享:基于 Rokid CXR-M SDK 构建「AI远程协作助手」实战全记录
人工智能·kotlin·sdk·rokid
mahuan1688881 小时前
ITVDesk
人工智能
聚梦小课堂2 小时前
用于大语言模型后训练阶段的新方法GVPO(Group Variance Policy Optimization)
人工智能·语言模型·后训练
说私域2 小时前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的互联网运营体系化研究
人工智能·小程序
谢栋_2 小时前
基于 GitLab CI/CD 与 Google Gemini 的 AI Code Review 自动化方案
人工智能·ci/cd·gitlab