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

How to apply for loop using python to avoid manual repeating

我写了一个代码,这是一个手动的方式,我需要使用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))

我想申请循环以避免手动处理。

类似于

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))

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