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

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

https://img1.sycdn.imooc.com/65965ce600014c7305130562.jpg

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


胡子哥哥
浏览 92回答 1
1回答

慕标5832272

您可以将图像路径的基本名称与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 necessaryplt.savefig('{dir_name}/{filename}'.format(dir_name=dir_name, filename=image_basename))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python