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

相关推荐
说私域2 小时前
从“高密度占有”到“点状渗透”:论“开源AI智能名片链动2+1模式”在S2B2C商城小程序中的渠道革新
人工智能·小程序
limenga1023 小时前
TensorFlow Keras:快速搭建神经网络模型
人工智能·python·深度学习·神经网络·机器学习·tensorflow
KG_LLM图谱增强大模型5 小时前
Vgent:基于图的多模态检索推理增强生成框架GraphRAG,突破长视频理解瓶颈
大数据·人工智能·算法·大模型·知识图谱·多模态
AKAMAI5 小时前
企业如何平衡AI创新与风险
人工智能·云原生·云计算
TDengine (老段)7 小时前
优化 TDengine IDMP 面板编辑的几种方法
人工智能·物联网·ai·时序数据库·tdengine·涛思数据
数据的世界017 小时前
Visual Studio 2026 正式发布:AI 原生 IDE 与性能革命的双向突破
ide·人工智能·visual studio
shayudiandian9 小时前
深度学习中的激活函数全解析:该选哪一个?
人工智能·深度学习
视界先声9 小时前
如何选择合适的养老服务机器人
人工智能·物联网·机器人
RPA机器人就选八爪鱼9 小时前
RPA财务机器人:重塑财务效率,数字化转型的核心利器
大数据·数据库·人工智能·机器人·rpa