如何提取图像以便对getcolors类进行分析

2024-04-19 17:05:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序来分析图像(绘画、素描等)。dominant_color函数应该返回一个元组列表[(count, (r#, b#, g#)), ...],按count降序排序。你知道吗

下面是脚本,但我不确定如何正确地给filename一个有效值。你知道吗

我试过filename = 'path to file',但是得到了syntax error,除非代码是在PyCharm中运行的。你知道吗

def dominant_color(filename):
    #Resizing parameters
    width, height = 150,150
    image = Image.open(filename)
    image = image.resize((width, height), resample = 0)
    #Convert image to RGB
    im_rgb = im.convert('RGB')
    #Get colors from image object
    pixels = image.getcolors(width * height)
    #Sort them by count number(first element of tuple)
    sorted_pixels = sorted(pixels, key=lambda t: t[0])
    return sorted_pixels

问题:

  1. 调用路径为filenamedominant_color时,会发生syntax error
  2. sorted_pixels列表不会首先返回最主要的颜色。你知道吗

预期输出:

  1. 从命令行运行代码时不出错
  2. sorted_pixels应按降序返回。你知道吗

Tags: to代码image列表counterrorfilenamewidth
2条回答

确保将文件路径作为原始字符串传递。 我的意思是这样写文件路径:

filename=r'C:\deve.jpg'

使用pathlib查找文件

from PIL import Image
from pathlib import Path
from pprint import pprint as pp


def dominant_color(filename):

    width, height = 150, 150
    image = Image.open(p)

    image = image.resize((width, height), resample=0)

    # Convert image to RGB
    im_rgb = image.convert('RGB')  # the original code was incorrectly im.convert

    # Get colors from image object
    pixels = image.getcolors(width * height)

    # Sort them by count number(first element of tuple)
    sorted_pixels = sorted(pixels, key=lambda t: t[0], reverse=True)

    return sorted_pixels


# p = Path.cwd().parent / 'IMG_3834.JPG'

or

# p = r'e:\PythonProjects\stack_overflow\IMG_3834.JPG'

or

p = 'e:/PythonProjects/stack_overflow/IMG_3834.JPG''

sorted_pixels = dominant_color(p)

pp(sorted_pixels[:5])

输出:

[(30, (244, 244, 244)),
 (30, (243, 243, 243)),
 (22, (242, 242, 242)),
 (15, (5, 5, 5)),
 (14, (245, 245, 245)),

从命令行:

  • 注意文件路径p是如何构建的
  • 还有其他方法可以向函数提供文件列表,但这是堆栈溢出中已经讨论过的另一个问题。你知道吗
  • 我的猜测是,从PyCharm运行时没有问题,因为映像与函数运行的目录相同,而从其他地方运行函数时可能不是这样。你知道吗

enter image description here

相关问题 更多 >