目标检测图像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(size0/h,size1/w)

new_h,new_w = int(h*r),int(w*r)

top = int((size0-new_h)/2)

left = int((size1-new_w)/2)

bottom = size0-new_h-top

right = size1-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 =label10

x = float(label11)

y = float(label12)

w = float(label13)

h = float(label14)

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

相关推荐
Shockang9 小时前
AI 设计工作流全景拆解:Figma MCP / Claude Design / Codex / Google Stitch
人工智能
To_OC10 小时前
数据集划分不是随便切:手把手切分大众点评情感数据集
人工智能·llm·agent
冬奇Lab11 小时前
每日一个开源项目(第142篇):android/skills - Google 官方 Android 开发 AI Skill 库
人工智能·开源·资讯
冬奇Lab11 小时前
Skill 系列(06):Skill 工程化与治理——路由准确率 38%、压缩节省 76%
人工智能·开源·agent
IT_陈寒13 小时前
Vue这个坑我跳了两次,原来问题出在这
前端·人工智能·后端
新新技术迷13 小时前
Node给AI接口做SSE代理与鉴权
人工智能
redreamSo14 小时前
大模型是不是到顶了?瓶颈到底在哪
人工智能·openai
Oo92014 小时前
Tool Use 背后的技术逻辑
人工智能
姗姗来迟了14 小时前
Vue3封装AI流式对话组件踩坑实录
人工智能