如何生成结果作为图形标题以及与绘制图像相关的文件名?

How to generate result as the figure title along with filename connected with the plotted image?

我需要帮助,将测试结果和文件名放在一起作为评估图像的标题。我可以将测试结果生成为列表(见图),我可以将测试结果添加到图像上。我可以在图像顶部添加文件名。但是,我不能两者兼顾。不确定我做错了什么。谢谢你。

path = '/Users/minny/Desktop/A/png/file2/'
ref_images = glob.iglob(path + "*.png")  
all_ref_images = []  



for ref_path in ref_images:  
    ref_head, tail = os.path.splitext(ref_path) 
    image1 = Image.open(ref_path) 
    imgA= print(calculate_brightness(image1))
    #all_ref_images.append([imgA, ref_head])    
    ref_image = plt.imshow(image1)
    fig = plt.figure()
    
    
    plt.title(os.path.basename(ref_head)), plt.title(calculate_brightness(image1))
    
    
    #plt.axis("off")
def calculate_brightness(image):
greyscale_image = image.convert('L')
histogram = greyscale_image.histogram()
pixels = sum(histogram)
brightness = scale = len(histogram)

for index in range(0, scale):
    ratio = histogram[index] / pixels
    brightness += ratio * (-scale + index)

return 1 if brightness == 255 else brightness / scale

%%capture

 #gives a standard size image to view inline with the text
 def display_img(img, cmap=None):
     fig = plt.figure(figsize=(3,3))
     ax = fig.add_subplot(111)
     ax.imshow(img, cmap)
 

 path = '/Users/minny/Desktop/A/png/file2/'
 ref_images = glob.iglob(path + "*.png")  
 all_ref_images = []  

for ref_path in ref_images:  
    ref_head, tail = os.path.splitext(ref_path) 
    image1 = Image.open(ref_path) 
    imgA= print(calculate_brightness(image1))
    all_ref_images.append([imgB, ref_head])               
    fig = plt.figure()      
    ref_image = plt.imshow(image1)
    print(os.path.basename(ref_head))        
    #plt.axis("off")

    ref_image = plt.imshow(image1)
    image_basename = os.path.basename(ref_head)
    title = '\n'.join([image_basename, str(calculate_brightness(image1))])
    plt.title(title, loc='left')

    dir_name = '/Users/minny/Desktop/A/png/results/'
    plt.savefig('{dir_name}/{filename}'.format(dir_name=dir_name, filename=image_basename))

您可以将图像路径的基本名称与 calculate_brightness 函数的输出连接起来,并将结果设置为标题而不覆盖它们:

ref_image = plt.imshow(image1)
image_basename = os.path.basename(ref_head)
test_results = '\n'.join(map(str, calculate_brightness(image1)))
title = '\n'.join([image_basename, test_results])
plt.title(title, loc='left')

UPD: 如果calculate_brightness函数的结果是一个浮点数,你可以这样解决你的问题:

ref_image = plt.imshow(image1)
image_basename = os.path.basename(ref_head)
title = '\n'.join([image_basename, str(calculate_brightness(image1))])
plt.title(title, loc='left')

UPD2: 要将图像保存到指定文件夹,您可以使用 plt.savefig 方法:

dir_name = '/Users/minny/Desktop/A/png/file2/some_directory' # create directory if necessary
plt.savefig('{dir_name}/{filename}'.format(dir_name=dir_name, filename=image_basename))