马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
基础不扎实,在写入文件等地方总是不用循环就写不出来。比如想要把列表中的每个元素分行写入之类的,所以代码就一个一个循环乱七八糟的,大佬们能不能教一下如何精简代码?不求最短,而是最易读的设为最佳。import cv2
#打开标签
#这版尝试保存整张图分成多张图后的标签和图片
f = open('.\\label\\000006.txt')
f1 = open('10000061.txt','w+')
f2 = open('10000062.txt','w+')
f3 = open('10000063.txt','w+')
#读取标签中目标的坐标
data = []
newdata = []
le =[]
ri=[]
for line in f.readlines():
temp = line.split()
data.append(temp)
newdata = data.copy()
#这一段是裁剪图片的代码
img = cv2.imread('000006.png',1)
a=0
b = 370
height, width, depth = img.shape
for i in range(0,len(data)):
xmin = int(float(data[i][1])*width - 0.5*float(data[i][3])*width)
le.append(xmin)
xmax = int(float(data[i][1])*width + 0.5*float(data[i][3])*width)
ri.append(xmax)
if b in range(le[i],ri[i]):
b = ri[i] + 10
else:
pass
if i == len(data)-1:
dst1 = img[0:height, a:b]
#换成保存图片
cv2.imwrite('.\\save\\10000001'+'.png',dst1)
print(data)
for i in range(0,len(data)):
newdata[i][1]=(((le[i]+ri[i])/2)-a)/(b-a)
print(data)
newdata[i][3]=float(newdata[i][3])*width/(b-a)
for j in range(0,len(ri)):
if ri[j] in range(a,b):
for p in range(len(newdata[j])):
f1.write(str(newdata[j][p])+' ')
f1.write('\n')
f1.close()
print(newdata)
print(data)
a = b
b = b +370
le =[]
ri=[]
for i in range(0,len(data)):
xmin = int(float(data[i][1])*width - 0.5*float(data[i][3])*width)
le.append(xmin)
xmax = int(float(data[i][1])*width + 0.5*float(data[i][3])*width)
ri.append(xmax)
if b in range(le[i],ri[i]):
b = ri[i] + 10
else:
pass
if i == len(data)-1:
dst1 = img[0:height, a:b]
#换成保存图片
cv2.imwrite('.\\save\\10000002'+'.png',dst1)
for i in range(0,len(data)):
newdata[i][1]=(((le[i]+ri[i])/2)-a)/(b-a)
newdata[i][3]=float(data[i][3])*width/(b-a)
for j in range(0,len(ri)):
if ri[j] in range(a,b):
for p in range(len(newdata[j])):
f2.write(str(newdata[j][p])+' ')
f2.write('\n')
f2.close()
a = b
b = b +370
le =[]
ri=[]
for i in range(0,len(data)):
xmin = int(float(data[i][1])*width - 0.5*float(data[i][3])*width)
le.append(xmin)
xmax = int(float(data[i][1])*width + 0.5*float(data[i][3])*width)
ri.append(xmax)
if b in range(le[i],ri[i]):
b = ri[i] + 10
else:
pass
if i == len(data)-1:
dst1 = img[0:height, a:b]
#换成保存图片
cv2.imwrite('.\\save\\10000003'+'.png',dst1)
for i in range(0,len(data)):
newdata[i][1]=(((le[i]+ri[i])/2)-a)/(b-a)
newdata[i][3]=float(data[i][3])*width/(b-a)
for j in range(0,len(ri)):
if ri[j] in range(a,b):
for p in range(len(newdata[j])):
f3.write(str(newdata[j][p])+' ')
f3.write('\n')
f3.close()
|