Pythonを使い、画像内のバーコード情報の取得をしようと考えています。
画像内のバーコード情報自体の抽出はできているのですが、要素を取得できません。
取得の仕方を教えていただけないでしょうか
環境としては
Python : 2.7.13
OS : raspbian 9.4
です。
Python
1import cv2 2import zbar 3 4#image_path = "barcode_original1.jpg" 5#image_path = "barcode_original2.jpg" 6image_path = "barcode_original3.JPG" 7 8scanner = zbar.ImageScanner() 9scanner.parse_config('enable') 10 11im = cv2.imread(image_path) 12gray_im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) 13rows,cols = im.shape[:2] 14 15# convert to gray_scale using threshold 16ret, threshold_im = cv2.threshold(gray_im, 150, 255, cv2.THRESH_BINARY) 17# get contour by findContours() 18im, contours, hierarchy = cv2.findContours(threshold_im, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 19 20# get rectangle from contour 21# center_pt: rectangle's central coordinates 22# w: rectangle's width, h: height 23# angle: rectangle's anlge 24scanned_data = {} 25for contour in contours: 26 rect = cv2.minAreaRect(contour) 27 w = int(rect[1][0]) 28 h = int(rect[1][1]) 29 min_w = cols*0.1 30 min_h = rows*0.1 31 if w > min_w and h > min_h: 32 w_half = int(w*0.5) 33 h_half = int(h*0.5) 34 center_pt = (int(rect[0][0]), int(rect[0][1])) 35 top = center_pt[1] - h_half 36 right = center_pt[0] + w_half 37 bottom = center_pt[1] + h_half 38 left = center_pt[0] - w_half 39 angle = int(rect[2]) 40 M = cv2.getRotationMatrix2D(center_pt, angle, 1) 41 rotated_im = cv2.warpAffine(im.copy(), M, (cols,rows)) 42 zbar_image = zbar.Image(cols, rows, 'Y800', rotated_im.tostring()) 43 scanner.scan(zbar_image) 44 for symbol in zbar_image: 45 symbol_type = symbol.type 46 symbol_data = symbol.data 47 if(symbol_type not in scanned_data.keys()): 48 scanned_data[symbol_type] = [] 49 if symbol_data not in scanned_data[symbol_type]: 50 scanned_data[symbol_type].append(symbol_data) 51 del(zbar_image) 52 53# ここまでバーコード情報の取得 54 55print type(scanned_data) 56print scanned_data 57print scanned_data["ISBN10"]
result
1<type 'dict'> 2{'ISBN10': ['4797374772'], 'EAN13': ['1920055026000']} 3Traceback (most recent call last): 4 File "barcode_recognize2.py", line 62, in <module> 5 print scanned_data["ISBN10"] 6KeyError: 'ISBN10'
追記
Python
1for key,val in scanned_data.items(): 2 print "key : "+str(key)+" val : "+str(val) 3 print type(key) 4 print scanned_data[key]
のコードを追記したところ
result
1key : ISBN10 val : ['4797374772'] 2<type 'zbar.EnumItem'> 3['4797374772'] 4key : EAN13 val : ['1920055026000'] 5<type 'zbar.EnumItem'> 6['1920055026000']
となりました。
keyがstrだと思いこんでいたのが原因かもしれないです。
回答2件
あなたの回答
tips
プレビュー