使用 Tesseract OCR 从图像中提取文本并输入文本字段
Pulling text from an image and input into a textfield with Tesseract OCR
我正在使用 Tesseract OCR,我希望它拍摄图像并将选择性的词输入到文本字段中,我能够完整地拍摄整个图像并将其放入文本字段中,但我没有不知道如何将单独的单词放在单独的文本字段中。
有人可以为我指出正确的方向,或者说出我需要的函数和语句吗?
更新
我已经弄明白了,使用正则表达式可以从图像中提取特定文本。例如,假设您想从地址中提取邮政编码,然后通过 Tesseract OCR 运行 它。它将在图像中找到文本并将其输出为字符串。如果您不知道该怎么做,请直接提问,我会 post 单独问答。您获得了字符串,现在您想要提取邮政编码。
假设地址是
0000 Stainly St, Water, IA, 50703 -- 这是一个假地址
@IBOutlet weak var zipcode: UITextField!
override func viewDidLoad() {
zipcode.text = getZip()
}
//Gets the text from image
var recognizedText : String!
//Set up the extraction function for the text extractoin from the recognizedText
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange([=10=].range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
//Function to get zip from the text
func getZip() -> String {
//below is the regex pattern to get zipcodes
let zipAddress = matchesForRegexInText("\d{5}(?:[-\s]\d{4})?", text: recognizedText)
if zipAddress.isEmpty {
return "Could Not Identify, Tap to Enter Zipcode"
} else {
return zipAddress[0]
}
}
如果有人有任何问题,请随时提出。
我正在使用 Tesseract OCR,我希望它拍摄图像并将选择性的词输入到文本字段中,我能够完整地拍摄整个图像并将其放入文本字段中,但我没有不知道如何将单独的单词放在单独的文本字段中。
有人可以为我指出正确的方向,或者说出我需要的函数和语句吗?
更新
我已经弄明白了,使用正则表达式可以从图像中提取特定文本。例如,假设您想从地址中提取邮政编码,然后通过 Tesseract OCR 运行 它。它将在图像中找到文本并将其输出为字符串。如果您不知道该怎么做,请直接提问,我会 post 单独问答。您获得了字符串,现在您想要提取邮政编码。
假设地址是 0000 Stainly St, Water, IA, 50703 -- 这是一个假地址
@IBOutlet weak var zipcode: UITextField!
override func viewDidLoad() {
zipcode.text = getZip()
}
//Gets the text from image
var recognizedText : String!
//Set up the extraction function for the text extractoin from the recognizedText
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange([=10=].range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
//Function to get zip from the text
func getZip() -> String {
//below is the regex pattern to get zipcodes
let zipAddress = matchesForRegexInText("\d{5}(?:[-\s]\d{4})?", text: recognizedText)
if zipAddress.isEmpty {
return "Could Not Identify, Tap to Enter Zipcode"
} else {
return zipAddress[0]
}
}
如果有人有任何问题,请随时提出。