如何使用python申请循环以避免手动重复

时间:2018-02-23 12:47:18

标签: python-3.x for-loop python-3.5 repeat

我编写了一个手动方式的代码,我需要使用for循环自动化它,但我无法这样做,如何为下面给出的代码编写for循环:

此代码只是一个手动代码。

我想申请循环以避免手动过程..

from skimage.measure import compare_ssim
#import argparse
#import imutils
import cv2

img1="express.png"
img2="horizon.png"
img3="jazz.png"
img4="porter.png"
img5="westjet.png"
img6="e1.png"


# load the two input images
imageA = cv2.imread(img1)
imageB = cv2.imread(img2)
imageC = cv2.imread(img3)
imageD = cv2.imread(img4)
imageE = cv2.imread(img5)
imageF = cv2.imread(img6)


resized_imageA = cv2.resize(imageA, (256, 162))
resized_imageB = cv2.resize(imageB, (256, 162))
resized_imageC = cv2.resize(imageC, (256, 162)) 
resized_imageD = cv2.resize(imageD, (256, 162))
resized_imageE = cv2.resize(imageE, (256, 162))
resized_imageF = cv2.resize(imageF, (256, 162))     

#print (resized_imageA.shape)
#print (resized_imageB.shape)
#print (resized_imageC.shape)
#print (resized_imageD.shape)
#print (resized_imageE.shape)
#print (resized_imageF.shape)

# convert the images to grayscale
grayA = cv2.cvtColor(resized_imageA, cv2.COLOR_BGR2GRAY)
grayB = cv2.cvtColor(resized_imageB, cv2.COLOR_BGR2GRAY)
grayC = cv2.cvtColor(resized_imageC, cv2.COLOR_BGR2GRAY)
grayD = cv2.cvtColor(resized_imageD, cv2.COLOR_BGR2GRAY)
grayE = cv2.cvtColor(resized_imageE, cv2.COLOR_BGR2GRAY)
grayF = cv2.cvtColor(resized_imageF, cv2.COLOR_BGR2GRAY)


# compute the Structural Similarity Index (SSIM) between the two
# images, ensuring that the difference image is returned
(score, diff) = compare_ssim(grayA, grayB, full=True)
diff = (diff * 255).astype("uint8")
print("SSIM: {}".format(score))

(score, diff) = compare_ssim(grayA, grayC, full=True)
diff = (diff * 255).astype("uint8")
print("SSIM: {}".format(score))

(score, diff) = compare_ssim(grayA, grayD, full=True)
diff = (diff * 255).astype("uint8")
print("SSIM: {}".format(score))

(score, diff) = compare_ssim(grayA, grayE, full=True)
diff = (diff * 255).astype("uint8")
print("SSIM: {}".format(score))

(score, diff) = compare_ssim(grayA, grayF, full=True)
diff = (diff * 255).astype("uint8")
print("SSIM: {}".format(score))

我想申请循环以避免手动过程。

1 个答案:

答案 0 :(得分:2)

这样的东西
from skimage.measure import compare_ssim
import cv2
import glob
cv_img = []
imgs = glob.glob("*.png")
#imgs = ["express.png", "horizon.png", "jazz.png", "porter.png", "westjet.png", "e1.png"]

grays = []
for img in imgs:
    image = cv2.imread(img)
    resized_image = cv2.resize(image, (256, 162))
    gray = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY)
    grays.append(gray)

grayA, *other_grays = grays  # We could also do grayA, other_grays = grays[0], grays[1:]

for gray in other_grays:
    (score, diff) = compare_ssim(grayA, gray, full=True)
    diff = (diff * 255).astype("uint8") # We don't use the diff value anywhere
    print("SSIM: {}".format(score))

这个想法是循环一些容器,在这种情况下是一个包​​含文件名的列表。每当你发现自己重复代码(一遍又一遍地写同一行)时,你应该尝试将它封装在一个抽象层之后。在这种情况下,您不是单独处理每个文件,而是提出一系列处理单个文件的操作,然后依次将该序列应用于每个文件。