概述
处理一张图片
1)构建代码
import cv2
import os
def cut_one_image(img_path, txt_path):
# 读取txt文件信息
def read_list(txt_path):
pos = []
with open(txt_path, 'r') as file_to_read:
while True:
lines = file_to_read.readline()
# 整行读取数据
if not lines:
break
pass
# 将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号, 则传入‘,'字符。
p_tmp = [float(i) for i in lines.split(' ')]
pos.append(p_tmp)
# 添加新读取的数据
# Efield.append(E_tmp)
pass
return pos
# txt转换为box
def convert(size, box):
xmin = (box[1]-box[3]/2.)*size[1]
xmax = (box[1]+box[3]/2.)*size[1]
ymin = (box[2]-box[4]/2.)*size[0]
ymax = (box[2]+box[4]/2.)*size[0]
box = (int(xmin), int(ymin), int(xmax), int(ymax))
return box
image = cv2.imread(img_path)
pos = read_list(txt_path)
for i in range(len(pos)):
box = convert(image.shape, pos[i])
image = cv2.rectangle(image, (box[0], box[1]), (box[2],box[3]), (0,255,0), 1)
save_path = '1_'+ str(i)+'.jpg'
print(save_path)
img = image[box[1]:box[3], box[0]:box[2]]
cv2.imwrite(save_path, img)
2)执行代码
cut_one_image(img_path = "1.jpg", txt_path = "1.txt")
3)或者执行代码
def choose_one(img_folder, label_folder,i):
img_list = os.listdir(img_folder)
img_list.sort()
label_list = os.listdir(label_folder)
label_list.sort()
img_path = img_folder + "/" + img_list[i]
txt_path = label_folder + "/" + label_list[i]
cut_one_image(img_path = img_path, txt_path = txt_path)
choose_one(img_folder="./images", label_folder =
"./yolo_label", i=0)
更改i数值即可以
改进版本
1)构建代码
import cv2
import os
def cut_one_image(img_path, txt_path, path):
# 读取txt文件信息
def read_list(txt_path):
pos = []
with open(txt_path, 'r') as file_to_read:
while True:
lines = file_to_read.readline()
# 整行读取数据
if not lines:
break
pass
# 将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号, 则传入‘,'字符。
p_tmp = [float(i) for i in lines.split(' ')]
pos.append(p_tmp)
# 添加新读取的数据
# Efield.append(E_tmp)
pass
return pos
# txt转换为box
def convert(size, box):
xmin = (box[1]-box[3]/2.)*size[1]
xmax = (box[1]+box[3]/2.)*size[1]
ymin = (box[2]-box[4]/2.)*size[0]
ymax = (box[2]+box[4]/2.)*size[0]
box = (int(xmin), int(ymin), int(xmax), int(ymax))
return box
image = cv2.imread(img_path)
pos = read_list(txt_path)
for i in range(len(pos)):
box = convert(image.shape, pos[i])
image = cv2.rectangle(image, (box[0], box[1]), (box[2],box[3]), (0,255,0), 1)
save_path = path + '_' + str(i)+'.jpg'
print(save_path)
img = image[box[1]:box[3], box[0]:box[2]]
cv2.imwrite(save_path, img)
def choose_one(img_folder, label_folder,i):
img_list = os.listdir(img_folder)
img_list.sort()
label_list = os.listdir(label_folder)
label_list.sort()
img_path = img_folder + "/" + img_list[i]
path1 = img_path.split(".")[0].split("/")[1]
print(path1)
txt_path = label_folder + "/" + label_list[i]
cut_one_image(img_path = img_path, txt_path = txt_path, path = path1)
2)执行代码
choose_one(img_folder="images", label_folder =
"yolo_label", i=0)
更改i数值即可以
最后
以上就是包容便当为你收集整理的(一)根据yolo格式txt标签文件,在原图中截取目标图片并保存的全部内容,希望文章能够帮你解决(一)根据yolo格式txt标签文件,在原图中截取目标图片并保存所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复