Author:XuLiu Time:20211105 Function:使用OpenCV截取图片,命名id_c0022.jpg
Input:
1.txt文件
| id | x | y | w | h |
|---|---|---|---|---|
| 5673 | 573 | 98 | 94 | 69 |
2.一张大图片
Output:
命名为id_c_.jpg的截图
import cv2
import os
import codecs
def image_cut_save(path, x, y, w, h, save_path):
"""
所截区域图片保存
:param path: 图片路径
:param x: 区块左上角位置的像素点离图片左边界的距离
:param y:区块左上角位置的像素点离图片上边界的距离
:param x+w:区块右下角位置的像素点离图片左边界的距离
:param y+h:区块右下角位置的像素点离图片上边界的距离
:param save_path: 所截图片保存位置
"""
img = cv2.imread(path) # 打开图像
cropped = img[y:y+h, x:x+w]
cv2.imwrite(save_path, cropped)
# embed()
if __name__ == '__main__':
root_path = '/home/jy/xl/workstation/Datasets/Car/Car_dataset' #图片的路径
save_path = '/home/jy/xl/workstation/Datasets/Car/Car_dataset_Cut' #截圖的路径
txt_path = '/home/jy/xl/workstation/Datasets/Car/Dataset/IDAnnotations1' #txt的路径,包括id+目标检测的坐标
if not os.path.exists(save_path):
os.makedirs(save_path)
txt = os.listdir(txt_path)
for i in txt:
portion = os.path.splitext(i)
if portion[1] == '.txt':
image = portion[0]
pic_path = os.path.join(root_path, image) #图片的文件名
f = codecs.open(os.path.join(txt_path, i), mode='r', encoding='utf-8')
lines = f.readlines() #一个txt的文件的行数
for l in lines: #对每一行遍历
temp = l.split() #以空格分割
id = int(temp[0])
xmin = int(temp[1])
ymin = int(temp[2])
xmax = int(temp[3])
ymax = int(temp[4])
pic_save_dir_path = os.path.join(save_path, str(id) + '_'+image)
image_cut_save(pic_path, xmin, ymin, xmax, ymax, pic_save_dir_path)
# from IPython import embed
# embed()
f.close()



