-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpreprocessing.py
More file actions
76 lines (65 loc) · 2.33 KB
/
preprocessing.py
File metadata and controls
76 lines (65 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'''Tools to preprocess'''
import argparse
import os
import cv2
import numpy as np
from exceptions import BarcodeNotFoundError
def parse_arguments():
'''Setup an argparse instance with -inpath, -efd, -debug'''
parser = argparse.ArgumentParser(description='Get statistics from an image folder')
parser.add_argument('-inpath', type=dir_path, help='input folder path')
parser.add_argument('-mask', default =True, help = 'interactive manual maskign, only usable with a set of identical images' )
parser.add_argument('-debug', default=False, help='save debug images')
return parser.parse_args()
def dir_path(string):
'''Check for valid path'''
if os.path.isdir(string):
return string
else:
raise NotADirectoryError(string)
def show_images(images):
'''Display images using cv2.imshow'''
for image in images:
cv2.imshow('image', image)
cv2.waitKey(0)
def read_barcode(raw_img):
'''Read barcode and return barcode and bar object'''
try:
my_bar = pyzbar.decode(raw_img)
bar_id = my_bar.data.decode("utf-8")
except Exception as exc:
raise BarcodeNotFoundError from exc
return bar_id, my_bar
#TODO: remove contour filtering once possible
def imgappend(image):
'''return contours from image path'''
chip = cv2.imread(os.path.join(path,image))
binary = segmentation.segment_otsu(chip)
contours, __ = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
#temporary
contours = [contour for contour in contours if cv2.contourArea(contour) > 1000]
return contours
def get_mask(barcode, image, binary, dist=750):
(x,y,w,h) = barcode.rect
#expand rectangle
x1 = x - dist
y1 = y - dist
x2 = x + w + dist*2
y2 = y + h + dist
#generate mask based on barcode location
mask = np.ones(image.shape[:2],np.uint8)
mask[y1:y2,x1:x2] = 0
res = cv2.bitwise_and(binary,binary, mask = mask)
ret, res = cv2.threshold(res, 0, 255, cv2.THRESH_OTSU)
return res
def total_bound(cnts):
boxes = []
for c in cnts:
(x, y, w, h) = cv2.boundingRect(c)
boxes.append([x,y, x+w,y+h])
boxes = np.asarray(boxes)
left, top = np.min(boxes, axis=0)[:2]
right, bottom = np.max(boxes, axis=0)[2:]
upperleft = (left,top)
bottomright = (right, bottom)
return upperleft, bottomright