最近打算写一个简单的图片文字识别程序,想先从简单的ASCii码字符串开始。我们需要数据集,即各个字符对应的图片数据。Python的很多图像库可以办到。但是这次选择用Excel的VBA试下,因为Excel可以将单元格复制为图片。
代码语言:javascript复制Option Explicit
Sub generateImage():
Application.ScreenUpdating = False ‘关闭屏幕刷新
Columns("A:B").Select
With Selection
.Interior.PatternColorIndex = xlAutomatic
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter’居中对齐
.ColumnWidth = 4.38
.RowHeight = 50
'.Font.Name = "Calibri"
.Font.Name = "Arial"
.Font.Size = 30
End With
Dim i%, row%, symbol$
Dim rng
i = 33
Open "charts.txt" For Output As #1
Do While i < 127
row = i - 32
symbol = Chr(i)
Cells(row, 1) = symbol
Print #1, symbol ‘将字符一行一行地写入文本文件,与图片一一对应
Range("A" & row).CopyPicture Appearance:=xlPrinter, Format:=xlPicture
With ActiveSheet.ChartObjects.Add(0, 0, 36, 36).Chart
.Parent.Select
.Paste
.Export row & ".jpg", "JPG" ’导出图片到当前文件夹
.Parent.Delete
End With
'Range("B" & row).Select
'ActiveSheet.Paste
i = i 1
Loop
Close #1
Application.ScreenUpdating = False
End Sub
搞定!