def gen_faces_detect_no_errors():
	''' just check if codegen generates no errors '''

	block_size = (24,24)
	size = tuple([x*2 for x in block_size])

	cascade_filename = '../data/haarcascade_frontalface_alt.xml'
	cascade = parse_haar.parse_haar_xml(cascade_filename)

	args = {'haar_classifier':cascade}
	code = Code()
	code.set_generator(gen_code.gen_detect_faces_opt, block_size, args)

	# extract some data from simulator
	sim = Interpreter(code, [[0 for x in xrange(size[0])] for y in xrange(size[1])], block_size)
	nr_reg = sim.procs[0][0].nr_reg
	mem_size = sim.procs[0][0].memory.size
	del sim

	# run through instructions and apply some checks
	cnt = 0
	current_imm = 0
	for x in code.gen(code):
		if x.opcode() == 'imm':
			current_im = x.value
		# heuristic test, not all errors are detected as memw(rx, ry) is also possible
		if (x.opcode() == 'memr' and str(x.src) == 'imm') \
		or (x.opcode() == 'memw' and str(x.dest) == 'imm'):
			if current_im >= mem_size:
				raise IllegalInstructionException('memx out of bounds, addr = %i'%int(current_im))
		cnt+=1

	print '# instructions: %i'%cnt
def test_no_manual_alloc():
	''' Manual register allocation interferes with scoped_alloc. '''

	block_size = (22,22)
	size = tuple(x*2 for x in block_size)
	width, height = block_size
	pe_dim = (size[0]//width, size[1]//height)

	cascade_filename = '../data/haarcascade_frontalface_alt.xml'
	cascade = parse_haar.parse_haar_xml(cascade_filename)

	class TestCode(Code):
		def r(self, nr):
			raise Exception('Manual allocation')

	args = {'haar_classifier':cascade}
	code = TestCode()
	code.set_generator(gen_code.gen_detect_faces_opt, block_size, args)

	cnt = 0
	for x in code.gen(code): cnt += 1
	print cnt

	args = {'haar_classifier':cascade, 'pe_dim':pe_dim}
	code2 = TestCode()
	code.set_generator(gen_code.gen_detect_faces_fullintegral_opt, block_size, args)

	cnt2 = 0
	for x in code.gen(code): cnt2 += 1
	print cnt2
def test_compare_implementations():
	''' check if the to implementation of detect_faces yield the same result '''
	# settings
	cascade_filename = '../data/haarcascade_frontalface_alt.xml'
	image_filename = '../data/vakgroep128_64.png'

	def run_test(codegen_function, image, cascade, block_size):
		print 'running %s'%codegen_function.__name__
		print 'XXX histogram equalisation is not implemented yet, use violajones impl'
		print '    before executing simulator'
		image = reference.equalizeHist(image)

		width, height = block_size
		pe_dim = (len(image[0])//width, len(image)//height)

		# now execute the codegen
		code = Code()
		
		args = {'haar_classifier':cascade, 'pe_dim':pe_dim}
		code.set_generator(codegen_function, block_size, args)

		sim = Interpreter(code, image, block_size, 4)
		sim.run()

		detections_pixmap = sim.gen_output_image(1) # result is saved in first buffer

		# convert the number of rejections in the stages to detections
		detections = gen_code.convert_pixelmap_to_detections(detections_pixmap, cascade.size)
		return detections


	# load image and cascade
	cascade = parse_haar.parse_haar_xml(cascade_filename)
	print cascade

	image = imageio.read(image_filename)
	if not image: raise Exception('image %s not found or not supported'%image_filename)


	block_size = (64, 64)
	implementations = [\
		gen_code.gen_detect_faces,\
		gen_code.gen_detect_faces_stage_outer,\
		gen_code.gen_detect_faces_fullintegral]
	detections = [run_test(impl, image, cascade, block_size) for impl in implementations]
	for i in xrange(len(implementations)-1):
		d1 = detections[i]
		d2 = detections[i+1]
		n1 = implementations[i].__name__
		n2 = implementations[i+1].__name__
		assert d1 == d2
Example #4
0
def split_filter_haar_example(cascade_filename):
	cascade = parse_haar.parse_haar_xml(cascade_filename)
	print cascade

	# now apply it for the first cascade at some position
	position = (10, 6)
	block_size = 24

	stage = cascade.stages[0]
	for feature in stage.features:
		res = split_filter(feature, position, block_size)
		print res
		print '\n'.join([str(x) for x in feature.shapes])
		print '->'
		print '\n'.join([str(x) for x in res.shapes])
def test_detect_faces_fullintegral():
	''' check if whole program works '''
	# settings
	cascade_filename = '../data/haarcascade_frontalface_alt.xml'
	image_filename = '../data/vakgroep128_64.png'

	def run_test(image, cascade):
		block_size = (64, 64)
		im_size = len(image[0]), len(image)
		pe_dim = tuple(s//b for s, b in zip(im_size, block_size))

		print 'XXX histogram equalisation is not implemented yet, use violajones impl'
		print '    before executing simulator'
		image = reference.equalizeHist(image)

		args = {'haar_classifier': cascade, 'pe_dim':pe_dim}
		# now execute the codegen
		code = Code()
		code.set_generator(gen_code.gen_detect_faces_fullintegral_opt, block_size, args)
		#print '# instructions: %i'%(code.instr_size())

		sim = Interpreter(code, image, block_size, 4)
		sim.run()

		detections_pixmap = sim.gen_output_image(1) # result is saved in first buffer

		# convert the number of rejections in the stages to detections
		detections = gen_code.convert_pixelmap_to_detections(detections_pixmap, cascade.size)
		return detections

	def run_ref(image, cascade):
		return reference.detect_faces(image, cascade)

	# first load the cascade
	cascade = parse_haar.parse_haar_xml(cascade_filename)
	print cascade

	image = imageio.read(image_filename)
	if not image: raise Exception('image %s not found or not supported'%image_filename)

	detections_test = run_test(image, cascade)
	detections_ref = run_ref(image, cascade)
	assert detections_test == detections_ref
Example #6
0
def main(image_filename, cascade_filename, res_filename, use_multiscale = False):
	image = imageio.read(image_filename)

	haar_classifier = parse_haar.parse_haar_xml(cascade_filename)
	print str(haar_classifier)


	# parameters
	scale_factor = 1.2
	min_size = (40, 40)

	# process image
	detected_faces = []
	if use_multiscale:
		detected_faces = detect_faces_multiscale(image, haar_classifier, scale_factor, min_size)
	else:
		detected_faces = detect_faces(image, haar_classifier)

	res = visualisation.draw_faces(image, detected_faces)
	imageio.write(res_filename, res, 3)
def test_convert_to_ssa_vj_no_errors():
	''' Test if ssa conversion is sufficient to convert VJ codegen. '''
	from violajones import gen_code
	from violajones import parse_haar
	cascade_filename = '../data/haarcascade_frontalface_alt.xml'
	
	block_size = (32, 32)
	im_size = block_size
	pe_dim = tuple(s//b for s, b in zip(im_size, block_size))

	# first load the cascade
	cascade = parse_haar.parse_haar_xml(cascade_filename)
	# use single stage to speed up test
	cascade.stages = [cascade.stages[0]]
	args = {'pe_dim': pe_dim, 'haar_classifier':cascade}
	
	block_len = 100 
	convertor = CodegenToSSAConvertor(block_len)
	test_code_total = []
	for i, current_ref_code in enumerate(convertor.gen_ssa_fragments(gen_code.gen_detect_faces_fullintegral, Code(), block_size, args)):
		test_code = convert_compact_repr_to_obj(current_ref_code)
	assert test_code # we just want no errors
        return feature_width/cascade_size[0] * feature_height/cascade_size[1]


def average_norm_feature_size(stage, cascade_size):
        return sum(calc_norm_feature_size(f, cascade_size) for f in stage.features)/len(stage.features)

if __name__ == '__main__':
        import sys
        if len(sys.argv) < 2:
                print 'usage: %s cascadefile'%sys.argv[0]
                exit(1)
        opt_args = sys.argv[2:]
        save_plots = '--save-plots' in opt_args
        disable_show_plots = '--disable-show-plots' in opt_args
        cascade_name = sys.argv[1]
        cascade = parse_haar_xml(cascade_name)
        print cascade

        stages = range(len(cascade.stages))
        nr_features = [len(stage.features) for stage in cascade.stages]
        avg_feature_size = [average_norm_feature_size(stage, cascade.size) for stage in cascade.stages]

        print stages
        print nr_features
        print avg_feature_size


        import matplotlib.pyplot as plt
        import matplotlib.ticker as ticker
        from matplotlib.backends.backend_pdf import PdfPages
        import numpy as np
Example #9
0
			  help='show results of sweep, requires numpy and matplotlib')
	parser.add_option('--save_results', action='store_true', dest='save_results', default=False,\
			  help='save results of sweep dump as pdfs, requires numpy and matplotlib')
	parser.add_option('--codegen_implementation', dest='codegen_impl', default='gen_detect_faces',\
			  help='override the codegen implementation')
	(options, args) = parser.parse_args()

	result_file = options.output
	cascade_filename = options.cascade
	block_size = (int(options.block_size), int(options.block_size))

	if options.show_results or options.save_results:
		plot_res(result_file, options.save_results, not options.show_results)
		exit(0)

	cascade = parse_haar.parse_haar_xml(cascade_filename)
	# support for alternative codegen implementations
	codegen_implementation = gen_code.gen_detect_faces
	if options.codegen_impl:
		impl_name = options.codegen_impl
		try:
			# try to fetch name from
			codegen_implementation = getattr(gen_code, impl_name)
			print 'using implementation %s'%impl_name
		except Exception, e:
			print 'could not load custom implementation %s'%impl_name
			print 'error', str(e)

			print 'available implementations:'
			print '\n'.join(x for x in dir(gen_code) if 'gen_detect_faces' in x)
			exit(1)
Example #10
0
def default_argument_setup(cascade_filename='data/haarcascade_frontalface_alt.xml'):
	from violajones import parse_haar
	# cascade
	cascade = parse_haar.parse_haar_xml(cascade_filename)
	return {'haar_classifier':cascade}