def execute_HoughLines(proxy,obj):
''' find houghlines '''
# parameter from obj
canny1=obj.canny1
canny2=obj.canny2
rho=obj.rho
theta=obj.theta
threshold=obj.threshold
minLineLength =obj.minLineLength
maxLineGap =obj.maxLineGap
# load the image
try: img=obj.sourceObject.Proxy.img.copy()
except: img=cv2.imread(__dir__+'/icons/freek.png')
# find edges
# naechst zwei zeilen koennen wahrscheinlich weg. #+#
edges = cv2.Canny(img,canny1,canny2)
obj.Proxy.img = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,canny1,canny2)
xsize=img.shape[1]
ysize=img.shape[0]
# find lines
lines = cv2.HoughLinesP(edges,1,np.pi/180*theta,threshold, minLineLength = minLineLength, maxLineGap = maxLineGap)
k=0
fclines=[]
img = 0 *img
for l in lines:
k += 1
[[x1,y1,x2,y2]] = l
fl=tools.fcline(x1,-y1,x2,-y2)
fclines.append(fl)
print (x1,y1,x2,y2)
a=cv2.line(img,(x1,y1),(x2,y2),(0,255,0),1)
# data for following nodes
obj.Proxy.img=img
obj.Proxy.fclines=fclines
obj.Proxy.lines=lines
# method for extra calculations
obj.Proxy.__class__.linelengths=property(lambda self: linelengths(self))
obj.Proxy.__class__.directions=property(lambda self: directions(self))
python类COLOR_GRAY2RGB的实例源码
def match(self, im0, im1, hm0, hm1):
viz = False
mask0 = self.BG0.segment(im0)
mask1 = self.BG1.segment(im1)
im0 = im0 * (mask0>1e-10).astype('uint8')[:,:,np.newaxis]
im1 = im1 * (mask1>1e-10).astype('uint8')[:,:,np.newaxis]
if viz:
viz0 = np.copy(im0)
viz1 = np.copy(im1)
pts14 = []
for chan in range(14):
h0 = cv2.resize(hm0[:,:,chan], (ORIG_SIZE, ORIG_SIZE))
h1 = cv2.resize(hm1[:,:,chan], (ORIG_SIZE, ORIG_SIZE))
y0, x0 = argmax_2d(h0)
y1, x1 = argmax_2d(h1)
target = take_patch(im0, y0, x0, PATCH_SIZE)
region = take_patch(im1, y1, x1, REGION_SIZE)
res = cv2.matchTemplate(region, target, cv2.TM_CCOEFF_NORMED)
_, _, _, top_left = cv2.minMaxLoc(res)
top_left = top_left[::-1]
center_in_region = (top_left[0] + PATCH_SIZE, top_left[1] + PATCH_SIZE)
center_in_im1 = (center_in_region[0] + y1-REGION_SIZE,
center_in_region[1] + x1-REGION_SIZE)
if viz:
cv2.circle(viz0, (x0,y0), 3, (0,0,255), -1)
cv2.circle(viz1, tuple(center_in_im1[::-1]), 3, (0,0,255), -1)
pts14.append([x0, y0, center_in_im1[1],center_in_im1[0]])
if viz:
mask0 = cv2.cvtColor(mask0, cv2.COLOR_GRAY2RGB).astype('uint8')
mask1 = cv2.cvtColor(mask1, cv2.COLOR_GRAY2RGB).astype('uint8')
viz = np.concatenate((mask0, viz0,viz1, mask1),axis=1)
cv2.imshow("v", viz)
cv2.waitKey(1)
return np.array(pts14)
return viz, np.array(pts14)
#rv = np.copy(region)
#rv[center_in_region[0],center_in_region[1]] = (0,0,255)
#tv = cv2.resize(target, tuple(region.shape[:2][::-1]))
#hv = np.zeros((region.shape), dtype='float32')
#res = res - res.min()
#res = res / res.max() * 255
#res = cv2.cvtColor(res, cv2.COLOR_GRAY2RGB)
#hv[PATCH_SIZE:PATCH_SIZE+res.shape[0],PATCH_SIZE:PATCH_SIZE+res.shape[1],:] = res
#region = np.concatenate((region, rv, tv, hv), axis=1)
#cv2.imwrite("patchmatch/region{}.png".format(chan), region)
def load_idl_tf(idlfile, H, jitter):
"""Take the idlfile and net configuration and create a generator
that outputs a jittered version of a random image from the annolist
that is mean corrected."""
annolist = al.parse(idlfile)
annos = []
for anno in annolist:
anno.imageName = os.path.join(
os.path.dirname(os.path.realpath(idlfile)), anno.imageName)
annos.append(anno)
random.seed(0)
if H['data']['truncate_data']:
annos = annos[:10]
for epoch in itertools.count():
random.shuffle(annos)
for anno in annos:
try:
if 'grayscale' in H and 'grayscale_prob' in H:
I = imread(anno.imageName, mode = 'RGB' if random.random() < H['grayscale_prob'] else 'L')
if len(I.shape) < 3:
I = cv2.cvtColor(I, cv2.COLOR_GRAY2RGB)
else:
if len(I.shape) < 3:
continue
I = imread(anno.imageName, mode = 'RGB')
if I.shape[0] != H["image_height"] or I.shape[1] != H["image_width"]:
if epoch == 0:
anno = rescale_boxes(I.shape, anno, H["image_height"], H["image_width"])
I = imresize(I, (H["image_height"], H["image_width"]), interp='cubic')
if jitter:
jitter_scale_min=0.9
jitter_scale_max=1.1
jitter_offset=16
I, anno = annotation_jitter(I,
anno, target_width=H["image_width"],
target_height=H["image_height"],
jitter_scale_min=jitter_scale_min,
jitter_scale_max=jitter_scale_max,
jitter_offset=jitter_offset)
boxes, flags = annotation_to_h5(H,
anno,
H["grid_width"],
H["grid_height"],
H["rnn_len"])
yield {"image": I, "boxes": boxes, "flags": flags}
except Exception as exc:
print(exc)
def get_results(args, H, data_dir):
tf.reset_default_graph()
H["grid_width"] = H["image_width"] / H["region_size"]
H["grid_height"] = H["image_height"] / H["region_size"]
if args.frozen_graph:
graph = load_frozen_graph(args.graphfile)
else:
new_saver = tf.train.import_meta_graph(args.graphfile)
NUM_THREADS = 8
with tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=NUM_THREADS),
graph=graph if args.frozen_graph else None) as sess:
sess.run(tf.global_variables_initializer())
if args.frozen_graph:
x_in = graph.get_tensor_by_name('x_in:0')
pred_boxes = graph.get_tensor_by_name('add:0')
pred_confidences = graph.get_tensor_by_name('Reshape_2:0')
else:
new_saver.restore(sess, args.weights)
x_in = tf.get_collection('placeholders')[0]
pred_boxes, pred_confidences = tf.get_collection('vars')
#freeze_graph.freeze_graph("overfeat.pb", "", False, args.weights, "add,Reshape_2", "save/restore_all",
#"save/Const:0", "overfeat_frozen.pb", False, '')
pred_annolist = al.AnnoList()
included_extenstions = ['jpg', 'bmp', 'png', 'gif']
image_names = [fn for fn in os.listdir(args.datadir) if any(fn.lower().endswith(ext) for ext in included_extenstions)]
image_dir = get_image_dir(args)
subprocess.call('mkdir -p %s' % image_dir, shell=True)
for i in range(len(image_names)):
image_name = image_names[i]
if H['grayscale']:
orig_img = imread('%s/%s' % (data_dir, image_name), mode = 'RGB' if random.random() < H['grayscale_prob'] else 'L')
if len(orig_img.shape) < 3:
orig_img = cv2.cvtColor(orig_img, cv2.COLOR_GRAY2RGB)
else:
orig_img = imread('%s/%s' % (data_dir, image_name), mode = 'RGB')
img = imresize(orig_img, (H["image_height"], H["image_width"]), interp='cubic')
feed = {x_in: img}
start_time = time()
(np_pred_boxes, np_pred_confidences) = sess.run([pred_boxes, pred_confidences], feed_dict=feed)
time_2 = time()
pred_anno = al.Annotation()
pred_anno.imageName = image_name
new_img, rects = add_rectangles(H, [img], np_pred_confidences, np_pred_boxes,
use_stitching=True, rnn_len=H['rnn_len'], min_conf=args.min_conf, tau=args.tau, show_suppressed=args.show_suppressed)
print(time() - start_time)
pred_anno.rects = rects
pred_anno.imagePath = os.path.abspath(data_dir)
pred_anno = rescale_boxes((H["image_height"], H["image_width"]), pred_anno, orig_img.shape[0], orig_img.shape[1], test=True)
pred_annolist.append(pred_anno)
imname = '%s/%s' % (image_dir, os.path.basename(image_name))
misc.imsave(imname, new_img)
if i % 25 == 0:
print(i)
return pred_annolist
def main(_):
image_path = FLAGS.test
csv_path = os.path.splitext(image_path)[0] + ".csv"
# --------- load classifier ------- #
cascade = cv2.CascadeClassifier(FLAGS.cascade_xml)
model, x, keep_prob = get_nn_classifier()
# ---------- object detection ------------#
print 'starting detection of ' + FLAGS.test + '...'
img = utils.getImage(image_path)
img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
delta = [-2, -1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 0.99, 0.995, 0.999, 0.9995, 0.9999]
start = time.time()
candidates = cascade.detectMultiScale(img, scaleFactor=FLAGS.scaleFactor, minNeighbors=FLAGS.minNeighbors, maxSize=(FLAGS.max_window_size,FLAGS.max_window_size))
detected = nn_classification(candidates, img, model, x, keep_prob, delta)
elapsed = (time.time() - start)
print 'detection time: %d' % elapsed
# ------------- evaluation --------------#
ground_truth_data = utils.get_ground_truth_data(csv_path)
for j in xrange(0, len(delta)):
detected[j] = [Rect(x, y, w, h) for (x,y,w,h) in detected[j]]
tp, fn, fp = utils.evaluate(ground_truth_data, detected[j])
# ----------------output ----------------#
# image output
"""
img_out = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
for (x,y,w,h) in detected[j]:
cv2.rectangle(img_out, (x-w/2,y-h/2),(x+w/2,y+h/2), [0,255,0], 3)
for c in ground_truth_data:
cv2.circle(img_out, (c[0], c[1]), 3, [0,0,255],3)
output_file = "out" + '_' + str(datetime.datetime.now())
cv2.imwrite(FLAGS.output_dir + output_file + '.png', img_out)
"""
# csv output
with open(FLAGS.output_dir + FLAGS.out + '.csv', 'ab') as file:
writer = csv.writer(file, delimiter=',')
writer.writerow([FLAGS.test, str(elapsed), str(len(ground_truth_data)), delta[j], FLAGS.minNeighbors, FLAGS.scaleFactor,
str(len(detected[j])), str(tp), str(fp), str(fn)])
def main():
image_path = FLAGS.test
csv_path = os.path.splitext(image_path)[0] + ".csv"
# ------------ load classifier ---------- #
cascade = cv2.CascadeClassifier(FLAGS.cascade_xml)
# -------------- open image --------------#
img = utils.getImage(image_path)
img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
# ---------- object detection ------------#
print 'starting detection of ' + FLAGS.test + '...'
start = time.time()
detected = cascade.detectMultiScale(img, scaleFactor=FLAGS.scaleFactor, minNeighbors=FLAGS.minNeighbors, maxSize=(FLAGS.max_window_size, FLAGS.max_window_size))
elapsed = (time.time() - start)
print 'detection time: %d' % elapsed
# ------------- evaluation --------------#
detected = [Rect(x, y, w, h) for (x,y,w,h) in detected]
ground_truth_data = utils.get_ground_truth_data(csv_path)
tp, fn, fp = utils.evaluate(ground_truth_data, detected)
# ----------------output ----------------#
# image output
"""
img_out = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
for c in ground_truth_data:
cv2.circle(img_out, (c[0], c[1]), 3, [0,0,255],3)
for r in detected:
cv2.rectangle(img_out, (r.x, r.y), (r.x2(), r.y2()), [0,255,0], 2)
output_file = "out" + '_' + str(datetime.datetime.now())
cv2.imwrite(FLAGS.output_dir + output_file + '.png', img_out)
"""
# csv output
with open(FLAGS.output_dir + 'results.csv', 'ab') as file:
writer = csv.writer(file, delimiter=',')
writer.writerow([FLAGS.test, str(elapsed),str(len(ground_truth_data)), str(FLAGS.scaleFactor),
str(FLAGS.minNeighbors), str(len(detected)), str(tp), str(fp), str(fn)])