我有一个程序来查找图像的方向。为了使其在任何其他方向上都是直的图像,我使用其旋转pred_val
(使用Pytorch)旋转它,因此我将其创建为字典,其中pred_val
askey
和图像名称为value
。我部分实现了它,但是作为一个例外,我知道如果一个或多个图像具有相同的图像,那么pred_val
只会分配最后一个图像名称,因此我得出这样的结论:
for k, v in dictImgNamValues.items(): #k-pred,v-image
if ',' in v:
for v in v.split(','):
imname = v[:-4]
print(k,v)
if os.path.isfile(image_folder+'/'+v):
if k == '0':
print('a')
image = cv2.imread(rot_img+'/'+file1+'/'+v)
rotImg = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)
cv2.imwrite(save_path+'/'+imname+'.png',rotImg)
elif k == '1':
print('b')
image = cv2.imread(rot_img+'/'+file1+'/'+v)
rotImg = cv2.rotate(image, cv2.ROTATE_180)
cv2.imwrite(save_path+'/'+imname+'.png',rotImg)
elif k =='2':
print('c')
image = cv2.imread(rot_img+'/'+file1+'/'+v)
rotImg = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
cv2.imwrite(save_path+'/'+imname+'.png',rotImg)
elif k=='3':
print('d')
image = cv2.imread(rot_img+'/'+file1+'/'+v)
cv2.imwrite(save_path+'/'+imname+'.png',image)
imname = v[:-4]
print(k,v)
if os.path.isfile(image_folder+'/'+v):
if k == '0':
print('a')
image = cv2.imread(rot_img+'/'+file1+'/'+v)
rotImg = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)
cv2.imwrite(save_path+'/'+imname+'.png',rotImg)
elif k == '1':
print('b')
image = cv2.imread(rot_img+'/'+file1+'/'+v)
rotImg = cv2.rotate(image, cv2.ROTATE_180)
cv2.imwrite(save_path+'/'+imname+'.png',rotImg)
elif k =='2':
print('c')
image = cv2.imread(rot_img+'/'+file1+'/'+v)
rotImg = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
cv2.imwrite(save_path+'/'+imname+'.png',rotImg)
elif k=='3':
print('d')
image = cv2.imread(rot_img+'/'+file1+'/'+v)
cv2.imwrite(save_path+'/'+imname+'.png',image)
看起来如此Elaborative方法字典还有其他方法可以将其缩短吗?
据我了解,在您的字典中-只是一个存储空间?那为什么不使用元组列表呢?我看不到您使用dict的任何特定功能,因此可以将其替换为更好的选项。
说:
dictImgNamValues = [(<pred_val1>, <nam1>), (<pred_val2>, <name2>), ...]
然后,您的代码将几乎相同。我对其进行了重构以减少代码重复。imname = v[:4]
虽然不知道为什么你写了两次之后仍然有份。Ayway:
rotation = {'0': cv2.ROTATE_90_COUNTERCLOCKWISE,
'1': cv2.ROTATE_180,
'2': cv2.ROTATE_90_CLOCKWISE}
for pred_val, name in dictImgNamValues: #k-pred,v-image
for name in name.split(','):
imname = name[:-4]
if os.path.isfile(image_folder +'/' + name):
image = cv2.imread(rot_img +'/' + file1 +'/' + name)
if pred_val in rotation:
image = cv2.rotate(image, rotation[pred_val])
cv2.imwrite(save_path + '/' + imname + '.png', image)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句