如何使用PIL分析python中的位图图像?

Unk*_*wen 5 python analysis image bitmap python-imaging-library

我想知道你是如何使用Python Imaging Library来分析一个简单的位图图像(比如位图在顶部有一条粗黑线)来告诉程序是图像的顶部.当找到黑线时,可能会输出一条消息.

任何示例代码都将是一个很大的帮助.

pan*_*ita 8

您可以将图片转换为rgb(红色,蓝色,绿色).例如,从这里获取一张照片:

https://github.com/panditarevolution/PIL_Play/blob/master/blackline.jpg

import PIL

# The conversion should work equally with a bitmap
img = PIL.Image.open("blackline.jpg")
rgb_im = img.convert('RGB')

rgb_im.size
Run Code Online (Sandbox Code Playgroud)

这将返回像素数的大小:(680,646).您可以查询单个像素的颜色,rgb_im.getpixel((x,y))其中哪里x是水平的并且y是垂直的,从上到下我相信.

因此,要检查第一行是否全黑(或大多数是黑色),您可以执行以下操作:

# Get the first row rgb values
first_row = [rgb_im.getpixel((i,0)) for i in range(rgb_im.size[0])]
# Count how many pixels are black. Note that jpg is not the cleanest of all file formats. 
# Hence converting to and from jpg usually comes with some losses, i.e. changes in pixel values. 
first_row.count((0,0,0)) # --> 628
len(first_row) #--> 680
Run Code Online (Sandbox Code Playgroud)

628/680 =第一行中92%的像素是黑色的.

让我们检查第一行中出现的所有颜色,set(first_row)以便我:

{(0, 0, 0),
 (0, 0, 2),
 (0, 1, 0),
 (1, 0, 0),
 (1, 1, 1),
 (2, 2, 0),
 (2, 2, 2),
 (4, 4, 2),
 (4, 4, 4),
 (5, 5, 3),
 (5, 7, 6),
 (6, 6, 4),
 (7, 7, 5),
 (14, 14, 12),
 (14, 14, 14),
 (35, 36, 31),
 (52, 53, 48),
 (53, 54, 46),
 (63, 64, 59),
 (64, 65, 60),
 (66, 67, 61),
 (68, 69, 61),
 (76, 77, 71),
 (79, 82, 65),
 (94, 96, 83),
 (96, 98, 87),
 (99, 101, 90),
 (101, 103, 92)}
Run Code Online (Sandbox Code Playgroud)

因此,即使有大约8%的非黑色像素,我们也可以看到其中大部分是非常单色的,即灰色阴影; 每种颜色的rgb值彼此相当接近.

这里有一个关于PIL的好教程:http: //effbot.org/imagingbook/

可在此处找到基本概述:http: //infohost.nmt.edu/tcc/help/pubs/pil.pdf

作为奖励,并且不知道它是否好(或者它是否涵盖PIL),有一个免费的草稿"用Python编程计算机视觉"在这里:http: //programmingcomputervision.com/