【发布时间】:2010-12-31 16:35:42
【问题描述】:
我还是个初学者,但我想写一个字符识别程序。这个程序还没有准备好。而且我编辑了很多,因此 cmets 可能不完全匹配。我将使用 8-connectivity 进行连接组件标记。
from PIL import Image
import numpy as np
im = Image.open("D:\\Python26\\PYTHON-PROGRAMME\\bild_schrift.jpg")
w,h = im.size
w = int(w)
h = int(h)
#2D-Array for area
area = []
for x in range(w):
area.append([])
for y in range(h):
area[x].append(2) #number 0 is white, number 1 is black
#2D-Array for letter
letter = []
for x in range(50):
letter.append([])
for y in range(50):
letter[x].append(0)
#2D-Array for label
label = []
for x in range(50):
label.append([])
for y in range(50):
label[x].append(0)
#image to number conversion
pix = im.load()
threshold = 200
for x in range(w):
for y in range(h):
aaa = pix[x, y]
bbb = aaa[0] + aaa[1] + aaa[2] #total value
if bbb<=threshold:
area[x][y] = 1
if bbb>threshold:
area[x][y] = 0
np.set_printoptions(threshold='nan', linewidth=10)
#matrix transponation
ccc = np.array(area)
area = ccc.T #better solution?
#find all black pixel and set temporary label numbers
i=1
for x in range(40): # width (later)
for y in range(40): # heigth (later)
if area[x][y]==1:
letter[x][y]=1
label[x][y]=i
i += 1
#connected components labeling
for x in range(40): # width (later)
for y in range(40): # heigth (later)
if area[x][y]==1:
label[x][y]=i
#if pixel has neighbour:
if area[x][y+1]==1:
#pixel and neighbour get the lowest label
pass # tomorrows work
if area[x+1][y]==1:
#pixel and neighbour get the lowest label
pass # tomorrows work
#should i also compare pixel and left neighbour?
#find width of the letter
#find height of the letter
#find the middle of the letter
#middle = [width/2][height/2] #?
#divide letter into 30 parts --> 5 x 6 array
#model letter
#letter A-Z, a-z, 0-9 (maybe more)
#compare each of the 30 parts of the letter with all model letters
#make a weighting
#print(letter)
im.save("D:\\Python26\\PYTHON-PROGRAMME\\bild2.jpg")
print('done')
【问题讨论】:
-
嗯...魔鬼在细节中。为了使其正常工作,我认为您需要加载许多不同的字体。我的预感是 OCR 程序会循环使用各种字体,直到找到他们喜欢的字体。显然,有很多关于这个主题的论文发表。为什么要将其作为您的第一个 Python 任务之一来实现?
-
更多说明:如果您的代码是黑白的,一切都很好。但是,如果某些字母/单词是灰色的怎么办?您需要类似 Gimp 的“按颜色给定阈值选择区域”操作。我个人会从计算暗度分布开始 - 平均暗度 + 图像的标准。然后我会从一个“白色”点开始,继续选择白色,直到我识别出非白色的岛屿——那些是潜在的字母。顺便说一句,您不需要随机性 - 广度优先搜索也可以帮助您定位所有黑色像素......诀窍在于定位岛屿。
-
我的幼稚方法是:a)找到一个 iland,b)包围它,c)记住它在测试中的原始位置,d)从图像中删除它(将剩余区域涂成白色)和将其附加到要处理的迷你图像列表中……这是一种开始。我个人会阅读现有方法,因为线性代数和统计等可能会为你打包一些非常强大的东西。
-
对……您刚刚描述了广度优先搜索。查一下。我建议通过 DFS,因为你可以在 N 个像素后停下来吃一个球而不是意大利面(不是那么重要)——因为这对于一个字母来说太大了。
-
没错,理论上 DFS 和 BFS 应该计算相同的东西。在这种情况下,我更喜欢 BFS,因为它还可以为您计算级别 - 可以帮助您“剥洋葱”。
标签: python arrays artificial-intelligence ocr