I was wondering how you use Python Imaging Library to analyse a simple bitmap image (say the bitmap has a thick black line at the top) to tell the program were the top of the image is. Maybe output a message when the black line is found.
Any example code would be a great help.
You could convert the picture to rgb which is (red,blue,green). For instance, get a picture from here:
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
This returns the size in number of pixels: (680,646)
. You can query the color of individual pixels with rgb_im.getpixel((x,y))
where x
goes horizontal and y
goes vertical, from top to bottom I believe.
So to check whether the first line is all black (or mostly black), you could do something like this:
# 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
628/680 = 92% of the pixels in the first row are black.
Let's check all occurring colors in the first row with set(first_row)
which gives me:
{(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)}
So even if there are around 8% non black pixels, we can see that most of these are pretty monochrome, ie shades of gray; the rgb values are fairly close to each other for each color.
There is a good tutorial on PIL here: http://effbot.org/imagingbook/
A basic overview can be found here: http://infohost.nmt.edu/tcc/help/pubs/pil.pdf
As a bonus, and without knowing whether it's good or not (or whether it covers PIL), there is a free draft of "Programming Computer Vision with Python" available here: http://programmingcomputervision.com/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.