<jupyter_start><jupyter_text>计算距离先对compute_dists_dirs.py脚本进行修改，使之能够在jupyter下运行起来。<jupyter_code>import argparse
import os
import models
from util import util

#parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
#parser.add_argument('-d0','--dir0', type=str, default='./imgs/ex_dir0')
#parser.add_argument('-d1','--dir1', type=str, default='./imgs/ex_dir1')
#parser.add_argument('-o','--out', type=str, default='./imgs/example_dists.txt')
#parser.add_argument('--use_gpu', action='store_true', help='turn on flag to use GPU')

#opt = parser.parse_args()

dir0 = './imgs/ex_dir0'
dir1 = './imgs/ex_dir1'
out = './imgs/example_dists.txt'
use_gpu = False


## Initializing the model
model = models.PerceptualLoss(model='net-lin',net='alex',use_gpu=use_gpu)

# crawl directories
f = open(out,'w')
files = os.listdir(dir0)

for file in files:
    
	if(os.path.exists(os.path.join(dir1,file))):
		# Load images
		img0 = util.im2tensor(util.load_image(os.path.join(dir0,file))) # RGB image from [-1,1]
		img1 = util.im2tensor(util.load_image(os.path.join(dir1,file)))

		if(use_gpu):
			img0 = img0.cuda()
			img1 = img1.cuda()

		# Compute distance
		dist01 = model.forward(img0,img1)
		print('%s: %.3f'%(file,dist01))
		f.writelines('%s: %.6f\n'%(file,dist01))

f.close()<jupyter_output>Setting up Perceptual loss...
Loading model from: /Users/diaosiji/PerceptualSimilarity/models/weights/v0.1/alex.pth
...[net-lin [alex]] initialized
...Done
backpack_00240.png: 0.344
backpack_00254.png: 0.375
backpack_00268.png: 0.344
backpack_00255.png: 0.378
backpack_00241.png: 0.371
backpack_00257.png: 0.318
backpack_00243.png: 0.302
backpack_00242.png: 0.245
backpack_00256.png: 0.284
backpack_00252.png: 0.394
backpack_00246.png: 0.474
backpack_00247.png: 0.269
backpack_00253.png: 0.477
backpack_00245.png: 0.390
backpack_00251.png: 0.383
backpack_00250.png: 0.338
backpack_00244.png: 0.305
backpack_00237.png: 0.332
backpack_00236.png: 0.298
backpack_00234.png: 0.333
backpack_00235.png: 0.313
backpack_00231.png: 0.333
backpack_00230.png: 0.308
backpack_00232.png: 0.271
backpack_00233.png: 0.271
backpack_00229.png: 0.327
backpack_00228.png: 0.336
backpack_00238.png: 0.306
backpack_00239.png: 0.307
backpack_00261.png: 0.384
backpack_00249.png: 0.351
backpack_00248.png: 0.343
backpack_002[...]<jupyter_text>修改目标- 增加一个路径参数dir2。这样可以dir0放原图（鞋子+logo），dir1放生成图（鞋子+logo的轮廓图经pix2pix输出的生成图），dir2放添加生成图（无logo鞋子轮廓经pix2pix输出的生成图+logo）；- 在在dir0的遍历循环中，增加一个代码段，用于判断dir2中是否存在同名文件，如果是，则同样进行比对，计算dir2中图片与原图的距离；- 计算出来的距离数据应该放到Nx2的张量中，便于比较计算均值，方差等； 导入依赖<jupyter_code>import argparse
import os
import models
from util import util

# for compute
import numpy as np
import torch<jupyter_output><empty_output><jupyter_text>设置参数<jupyter_code># ex_dir0用于放置物体加logo原图
dir0 = './imgs/ex_dir0'

# ex_dir1用于放置cGAN直接生成图
dir1 = './imgs/ex_dir1'

# ex_dir2用于放置生成添加logo图
dir2 = './imgs/ex_dir2'

# ex_dir3用于发放至物体加logo图的轮廓提取图
dir3 = './imgs/ex_dir3'

# 输出计算结果的文件路径
out = './imgs/example_dists.txt'

# 是否使用GPU
use_gpu = False<jupyter_output><empty_output><jupyter_text>初始化模型及记录文件<jupyter_code>## Initializing the model
model = models.PerceptualLoss(model='net-lin',net='alex',use_gpu=use_gpu)

# crawl directories 不需要这个文件
#f = open(out,'w')<jupyter_output>Setting up Perceptual loss...
Loading model from: /Users/diaosiji/PerceptualSimilarity/models/weights/v0.1/alex.pth
...[net-lin [alex]] initialized
...Done<jupyter_text>主循环- 修改1：取消文件写入，直接在笔记内计算即可；OK- 修改2：添加一个新的目录dir2；OK- 注意：dir1、2、3内的图片命名和后缀都要一致，如果是jpg和png就不行。可以用mac批量替换后缀！模型输出的dist0x距离是torch.Tensor数据类型。<jupyter_code># 遍历原图文件夹内图片
files = os.listdir(dir0)
# 列表
dist01_list = []
dist02_list = []
dist03_list = []

for file in files:
    img0 = util.im2tensor(util.load_image(os.path.join(dir0,file))) # RGB image from [-1,1]
    # 这是在生成图目录
    #print(os.path.exists(os.path.join(dir1,file)))
    if(os.path.exists(os.path.join(dir1,file))):
        # Load images
        img1 = util.im2tensor(util.load_image(os.path.join(dir1,file)))
        #print(img1)

    # 这是在添加生成图目录
    #print(os.path.exists(os.path.join(dir2,file)))
    if(os.path.exists(os.path.join(dir2,file))):
        # Load images
        img2 = util.im2tensor(util.load_image(os.path.join(dir2,file)))
        
    # 这是在有logo原图的轮廓图的目录
    if(os.path.exists(os.path.join(dir3,file))):
        # Load images
        img3 = util.im2tensor(util.load_image(os.path.join(dir3,file)))

        if(use_gpu):
            img0 = img0.cuda()
            img1 = img1.cuda()
            img2 = img2.cuda()
            img3 = img3.cuda()

        # Compute distance
        # 原图和生成图距离
        dist01 = model.forward(img0,img1)
        #print(dist01.data.numpy()[0,0,0,0])
        dist01_list.append(dist01.data.numpy()[0,0,0,0])
        
        # 原图和添加生成图距离
        dist02 = model.forward(img0,img2)
        dist02_list.append(dist02.data.numpy()[0,0,0,0])
        
        # 原图和轮廓图距离
        dist03 = model.forward(img0,img3)
        dist03_list.append(dist03.data.numpy()[0,0,0,0])
        
        print('%s cGAN: %.3f augment: %.3f sketch: %.3f'%(file,dist01,dist02,dist03))
       
#print(dist01_list)
#print(dist02_list)
tensor1 = torch.Tensor(dist01_list)
tensor2 = torch.Tensor(dist02_list)
tensor3 = torch.Tensor(dist03_list)

print('cGAN mean distance with origin:', tensor1.mean())
print('cGAN distance std with origin:', tensor1.std())
print('augment mean distance with origin:', tensor2.mean())
print('augment distance std with origin:', tensor2.std())
print('sketch mean distance with origin:', tensor3.mean())
print('sketch distance std with origin:', tensor3.std())<jupyter_output>30_AB.png cGAN: 0.313 augment: 0.284 sketch: 0.525
53_AB.png cGAN: 0.210 augment: 0.188 sketch: 0.428
65_AB.png cGAN: 0.298 augment: 0.263 sketch: 0.538
14_AB.png cGAN: 0.226 augment: 0.197 sketch: 0.444
1_AB.png cGAN: 0.241 augment: 0.211 sketch: 0.502
51_AB.png cGAN: 0.165 augment: 0.141 sketch: 0.501
20_AB.png cGAN: 0.162 augment: 0.147 sketch: 0.418
16_AB.png cGAN: 0.188 augment: 0.152 sketch: 0.377
7_AB.png cGAN: 0.398 augment: 0.368 sketch: 0.565
59_AB.png cGAN: 0.274 augment: 0.226 sketch: 0.540
55_AB.png cGAN: 0.214 augment: 0.195 sketch: 0.575
28_AB.png cGAN: 0.265 augment: 0.241 sketch: 0.538
10_AB.png cGAN: 0.170 augment: 0.141 sketch: 0.466
34_AB.png cGAN: 0.338 augment: 0.317 sketch: 0.613
57_AB.png cGAN: 0.200 augment: 0.191 sketch: 0.436
26_AB.png cGAN: 0.211 augment: 0.153 sketch: 0.347
38_AB.png cGAN: 0.128 augment: 0.117 sketch: 0.357
9_AB.png cGAN: 0.150 augment: 0.114 sketch: 0.378
15_AB.png cGAN: 0.192 augment: 0.157 sketch: 0.501
52_AB.png cGAN: 0.273 augment: 0.2[...]
{'fraction_non_alphanumeric': 0.148221044663134, 'fraction_numerical': 0.11112793338380016, 'mean_word_length': 4.432565789473684, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '464618', 'license': 'MIT', 'n_tokens_mistral': 3420, 'n_tokens_neox': 3015, 'n_words': 468, 'path': 'PerceptualSimilarity/compute_dists_dirs2.ipynb', 'repo_name': 'diaosiji/CRUI', 'size': '6605'}