3 import sys, os, os.path, glob, math, cv2, string, random
4 from datetime import datetime
5 from optparse import OptionParser
8 from xml.dom import minidom
10 def resize(image, d_w, d_h):
11 if (d_h < image.shape[0]) or (d_w < image.shape[1]):
12 ratio = min(d_h / float(image.shape[0]), d_w / float(image.shape[1]))
14 kernel_size = int( 5 / (2 * ratio))
16 image_to_resize = cv2.filter2D(image, cv2.CV_8UC3, cv2.getGaussianKernel(kernel_size, sigma))
17 interpolation_type = cv2.INTER_AREA
19 image_to_resize = image
20 interpolation_type = cv2.INTER_CUBIC
22 return cv2.resize(image_to_resize,(d_w, d_h), None, 0, 0, interpolation_type)
24 def det2negative(xmldoc, opath):
25 samples = xmldoc.getElementsByTagName('sample')
26 for sample in samples:
27 detections = sample.getElementsByTagName('detections')
28 detections = minidom.parseString(detections[0].toxml())
29 detections = detections.getElementsByTagName("_")
30 if len(detections) is not 0:
31 path = sample.getElementsByTagName("path")
32 path = path[0].firstChild.nodeValue
33 mat = cv2.imread(path)
34 mat_h, mat_w, _ = mat.shape
36 for detection in detections:
37 detection = detection.childNodes
38 for each in detection:
39 rect = eval(re.sub( r"\b\s\b", ",", re.sub(r"\n", "[", each.nodeValue )) + "]")
42 ratio = 64.0 / rect[3]
45 mat = resize(mat, int(round(mat_w * ratio)), int(round(mat_h * ratio)))
47 rect[0] = int(round(ratio * rect[0])) - 10
48 rect[1] = int(round(ratio * rect[1])) - 10
49 rect[2] = rect[0] + 32 + 20
50 rect[3] = rect[1] + 64 + 20
52 cropped = mat[rect[1]:(rect[3]), rect[0]:(rect[2]), :]
53 img = os.path.join(opath, ''.join(random.choice(string.lowercase) for i in range(8)) + ".png")
54 cr_h, cr_w, _ = cropped.shape
55 if cr_h is 84 and cr_w is 52:
56 cv2.imwrite(img, cropped)
60 if __name__ == "__main__":
62 parser = OptionParser()
63 parser.add_option("-i", "--input", dest="input", metavar="DIRECTORY", type="string",
64 help="Path to the xml collection folder.")
66 parser.add_option("-d", "--output-dir", dest="output", metavar="DIRECTORY", type="string",
67 help="Path to store data", default=".")
69 (options, args) = parser.parse_args()
72 parser.error("Input folder is required.")
74 opath = os.path.join(options.output, datetime.now().strftime("negatives" + "-%Y-%m-%d-%H-%M-%S"))
77 gl = glob.iglob( os.path.join(options.input, "set[0][0]_V0[0][5].seq.xml"))
80 xmldoc = minidom.parse(f)
81 det2negative(xmldoc, opath)