【问题标题】:Accessing PIL image subelements, and taking a string from it访问 PIL 图像子元素,并从中获取字符串
【发布时间】:2014-10-05 08:09:29
【问题描述】:

目前我有一个图像,我想从示例中提取单个字符串,概述了下面的详细信息(假设图像已加载到内存中以供 PIL 访问)

# Image size of: Image[480,640] (Binary image for example)
# Take string from level (y = 200) from start to (x = 250)
Sample_binary = Image[x:1,y]

但是当我尝试访问它时,它会抛出一个错误,要求只输入一个整数(据我所知,它可能不使用Python Strings??),这意味着我只能访问一个像素,是无论如何,我可以从列(y = 200)上的图像行(x = 0 到 x = 250)的开头采样一行?

感谢您的宝贵时间

【问题讨论】:

    标签: python string variables python-imaging-library


    【解决方案1】:

    不使用 numpy 数组:

    from PIL import Image
    i = Image.open("basic_training.png")
    
    # get a line
    def get_line(i, y):
        pixels = i.load() # this is not a list, nor is it list()'able
        width, height = i.size
        all_pixels = []
        for xPos in range(width):
            cpixel = pixels[xPos, y]
            all_pixels.append(cpixel)
        return all_pixels
    
    # get a columns
    def get_column(i, x):
        pixels = i.load() # this is not a list, nor is it list()'able
        width, height = i.size
        all_pixels = []
        for yPos in range(height):
            cpixel = pixels[x, yPos]
            all_pixels.append(cpixel)
        return all_pixels
    
    line = get_line(i, y)
    print len(line)
    col = get_column(i, x)
    print len(col)
    

    get_line 给出一条线,给定它的 y 位置
    get_col 在给定 x 位置的情况下给出一列

    您对字符串、图像等的描述有点令人困惑。不知道你是否只想要一个像素,整行等。使用上面的代码,因为它返回一个普通的python列表,你可以','.join(col)他们或你需要的方式。

    【讨论】:

    • 对不起,我只是注意到图像的像素大小,真的应该说不同
    【解决方案2】:

    使用教程供参考:http://effbot.org/imagingbook/introduction.htm

    from PIL import Image
    im = Image.open("Image.jpg")
    box = (0, 200, 251, 201) # (left, upper, right, lower)
    region = im.crop(box)
    L = region.load()
    

    这使您可以从检索到的数据行中检索 RGB 字节:

    >>> L[0, 0]
    (98, 92, 44)
    >>> L[250, 0]
    (104, 97, 43)
    

    只是为了显示大小限制:

    >>> L[0, 1] # out of bounds
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: image index out of range
    >>> L[251, 0] # out of bounds
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: image index out of range
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 2021-08-06
      • 1970-01-01
      • 2020-01-09
      • 2014-09-20
      相关资源
      最近更新 更多