念数字python_我是怎样利用python PIL将图片数字读出来的?
一、需求來源
因為在編寫爬蟲程序時,經常會遇到,電話號碼使用圖片格式顯示。程序無法直接拿到其中的電話號碼。
二、解決思路
1、拿到該網站從0-9的數字的圖片,并將每個圖片轉換成相應的向量。
2、需要使用python讀取圖片。
3、將讀取出來的圖片分割開來。
4、將分割出來的數字圖片和已經轉換成向量的的圖片相比較。如果相等就返回該數值。
三、用到的模塊
1、urllib2
2、Image
3、cStringIO
4、os
四、上代碼
# -*- coding:utf-8 -*-
import os
from PIL import Image
import cStringIO
import urllib2
class Number2vector(object):
def __init__(self):
#在構造函數時就拿到{'數字':'向量'}的字典。
numdict = self.get_numberdict()
file_path = "phoneimage/phone3.png"
# 這里是將之前已經轉換為向量的數字拿到一個字典里面,方便之后的比對。
def get_numberdict(self):
numdict = dict()
path = "numbertxt"
file_list = os.listdir(path)
for filex in file_list:
filex = path + '/' + filex
f = open(filex)
c = f.read()
key = filex.split('/')[1].split('.')[0].replace('m', '')
numdict[key] = c
return numdict
#將圖片轉換為用0和1表示的字符串
def image2text(self, im):
width = im.size[0]
height = im.size[1]
tmstr = ""
for i in range(0,width):
for j in range(0,height):
cl=im.getpixel((i,j))
if(cl==0):
#黑色
tmstr = tmstr + "1"
else:
tmstr = tmstr + "0"
tmstr = tmstr + "\n"
return tmstr
# 用來比較向量是否相等。如果相等則返回該數字
def get_number(self, im):
text = self.image2text(im)
numdict = self.get_numberdict()
keys = list()
vals = list()
for k, v in numdict.items():
keys.append(k)
vals.append(v)
if text in vals:
i = vals.index(text)
return keys[i]
else:
return None
def splitimage(self,file_path):
region_list = list()
# 判斷該文件是本地文件還是web文件。
if "http://" in file_path or "https://" in file_path:
image = cStringIO.StringIO(urllib2.urlopen(file_path).read())
im = Image.open(image)
else:
im = Image.open(file_path)
width = im.size[0]
i = 0
while i < width - 9:
box = (i, 0, i+9, 25)
region = im.crop(box)
i += 9
region_list.append(region)
return region_list
def getimagefromweb(file_path):
file = cStringIO.StringIO(urllib2.urlopen(file_path).read())
def do_main(self, file_path = "phoneimage/phone3.png"):
region_list = self.splitimage(file_path)
strx = ""
for r in region_list:
tmpnum = self.get_number(r)
if tmpnum != None:
strx = strx + tmpnum
return strx
file_path = "這里填寫你的圖片路徑"
n = Number2vector()
print n.do_main(file_path)
五、備注
在之前準備工作中,我為了拿到準確的{"數字":"向量"}的鍵值對。需要多次進行比較。并且要拿到該網站中從0-9所有的數字。
總結
以上是生活随笔為你收集整理的念数字python_我是怎样利用python PIL将图片数字读出来的?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python的语言是什么歌_用pytho
- 下一篇: 卡诺尔瓷砖与鹰牌哪个好?