访问PIL图像子元素,并从中获取字符串

时间:2014-10-05 08:09:30

标签: python string variables python-imaging-library

目前我有一个图像,我只想从示例中抽取单个字符串,概述下面的详细信息(假设图像已加载到内存中以进行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)开始采样一条线?

谢谢你的时间

2 个答案:

答案 0 :(得分:0)

不使用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)或者你需要的方式。

答案 1 :(得分:0)

使用教程作为参考: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