根据json文件中的坐标剪切图像
import numpy as np
import cv2
import os
import json
import xml.etree.cElementTree as ET
def drawxml(xmlpath,im):
tree = ET.ElementTree(file=xmlpath)
print("resoluting...")
root = tree.getroot()
for obj in root:
if obj.tag == 'object':
objectname = obj[0].text # object name
box = []
print('name:' + objectname)
for bndbox in obj:
for sub in bndbox:
box.append(int(sub.text)) # bndbox
box = np.array(box)
# print(box)
cv2.rectangle(im,(box[0],box[1]),(box[2],box[3]),(0,255,0),2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(im,objectname,(box[0],box[1]),font,0.8,(255,255,255),2,cv2.LINE_AA)
return im
def drawjson(jsonpath, im):
xList=[]
yList=[]
jsonobj = json.load(open(jsonpath))
hats = jsonobj['shapes']
for hat in hats:
boxes = hat['points']
pts = np.array(boxes, np.int32)
pts = pts.reshape((-1, 1, 2))
# print(pts)
objectname = hat['label']
print(jsonpath)
print(objectname)
cv2.polylines(im, [pts], True, (0, 0, 255), 2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(im, objectname, (pts[0][0][0], pts[0][0][1]), font, 0.5, (255, 255, 255), 2, cv2.LINE_AA)
print(len(pts))
xlist=[]
ylist=[]
for i in range(len(pts)):
xlist.append(pts[i][0][0])
ylist.append(pts[i][0][1])
xList.append(xlist)
yList.append(ylist)
#print('xList',xList)
#print('yList',yList)
return im,xList,yList
if __name__ == '__main__':
#通过json或xml对原图进行标记需要填写savepath,通过json截取不用填写
imgpath = "C:/Users/123/Desktop/3/" #图片路径
xmlpath = "C:/Users/123/Desktop/4/" #xml路径
savepath = "" #画图路径(截取不用填写)
cutsavepath="C:/Users/123/Desktop/5/" #存放裁剪后的路径
jsonpath = "" #图片对应的json路径
imgnum = 0
xmlnum = 0
jsonnum = 0
for f in os.listdir(imgpath):
ifdraw = False
imgnum += 1
im = cv2.imread(imgpath + f)
origin=cv2.imread(imgpath + f)
xmlname = xmlpath + f.replace('.bmp', '.xml')
if (xmlpath!='' and os.path.exists(xmlname)):
ifdraw = True
im = drawxml(xmlname, im)
xmlnum += 1
jsonname = jsonpath + f.replace('.bmp', '.json')
if (jsonpath!='' and os.path.exists(jsonname)):
ifdraw = True
im,xList,yList = drawjson(jsonname, im)
jsonnum += 1
print('xList',xList)
print('yList',yList)
print(len(xList))
for i in range(len(xList)):
img_cut=origin[min(yList[i]):max(yList[i]),min(xList[i]):max(xList[i])]
print(img_cut)
if os.path.exists(cutsavepath+f):
cut_img_name=cutsavepath+'cutted-'+ str(i)+'-'+f
else: cut_img_name=cutsavepath+f
print(cut_img_name)
cv2.imwrite(cut_img_name,img_cut)
if ifdraw and savepath!='':
cv2.imwrite(savepath + f, im)
print("imgnum:", imgnum)
print("xmlnum:", xmlnum)
print("jsonnum", jsonnum)