目标检测图像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()

相关推荐
kakaZhui4 分钟前
【llm对话系统】大模型源码分析之 LLaMA 位置编码 RoPE
人工智能·深度学习·chatgpt·aigc·llama
struggle20251 小时前
一个开源 GenBI AI 本地代理(确保本地数据安全),使数据驱动型团队能够与其数据进行互动,生成文本到 SQL、图表、电子表格、报告和 BI
人工智能·深度学习·目标检测·语言模型·自然语言处理·数据挖掘·集成学习
佛州小李哥1 小时前
通过亚马逊云科技Bedrock打造自定义AI智能体Agent(上)
人工智能·科技·ai·语言模型·云计算·aws·亚马逊云科技
云空2 小时前
《DeepSeek 网页/API 性能异常(DeepSeek Web/API Degraded Performance):网络安全日志》
运维·人工智能·web安全·网络安全·开源·网络攻击模型·安全威胁分析
AIGC大时代2 小时前
对比DeepSeek、ChatGPT和Kimi的学术写作关键词提取能力
论文阅读·人工智能·chatgpt·数据分析·prompt
山晨啊83 小时前
2025年美赛B题-结合Logistic阻滞增长模型和SIR传染病模型研究旅游可持续性-成品论文
人工智能·机器学习
一水鉴天4 小时前
为AI聊天工具添加一个知识系统 之77 详细设计之18 正则表达式 之5
人工智能·正则表达式
davenian4 小时前
DeepSeek-R1 论文. Reinforcement Learning 通过强化学习激励大型语言模型的推理能力
人工智能·深度学习·语言模型·deepseek
X.AI6664 小时前
【大模型LLM面试合集】大语言模型架构_llama系列模型
人工智能·语言模型·llama
CM莫问4 小时前
什么是门控循环单元?
人工智能·pytorch·python·rnn·深度学习·算法·gru