根据目标检测结果裁剪bbox保存到本地,python,opencv

近日有一个需求是把检测的框的图像都截下来保存,就写了个脚本,分享出来

  • 基本逻辑为循环读取每张图片的结果坐标文件,读取框坐标,再用OpenCV的函数裁剪下来并保存。
  • 注意坐标文件为VOC格式,自行百度。
# coding=utf-8
import cv2
import os
import glob
import numpy as np
import re

def CutImg(imgpath,destpath):
	img = glob.glob(r"/DATACENTER6/ph/traffic_model_faster101/in_pic/29-6-ori/*.jpg")
	img_len= int(len(img))
	#get all the images 
	
	for i in range(img_len):
		temp=img[i].rstrip(".jpg")				# get image name to find its' annotation file.
		
		ori_img = cv2.imread(str(img[i]))
		sp = ori_img.shape						#obtain the image shape
		sz1 = sp[0] 							#height(rows) of image
		sz2 = sp[1] 							#width(colums) of image		

		np.set_printoptions(suppress=True)
		txt = np.loadtxt(str(temp)+".txt")		#load the pic's annotation, which is voc-style.
		if txt.shape[0]==0:						#if the annotation is null, drop it.
			continue
		if np.ndim(txt) == 1:					
			txt = txt.reshape(1, 5)

		txt_len=len(txt)
		# print(txt)
		# print(txt_len)
		for n in range(txt_len):				#get every object's coordinates in this image
			x1=txt[n][0]
			y1=txt[n][1]
			x2=txt[n][2]
			y2=txt[n][3]
			a=int(x1) # x start
			b=int(x2) # x end
			c=int(y1) # y start
			d=int(y2) # y end
			#print(a,b,c,d)
			res = ori_img[c:d,a:b]				#use opencv's function to cut the image.
			cv2.imwrite("/DATACENTER6/ph/traffic_model_faster101/in_pic/29-6-cut/"+str(i) +str(n)+ '-29-6.jpg',res) 


if __name__ == '__main__':
	imgpath ='./28-4' # source images
	txtpath ='./28-4-1'	
	destpath='./28-4-cut' # resized images saved here
	CutImg(imgpath,destpath)



评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值