def draw_rects(img, rects):
"""
?????????????
:param img:
:param rects:
:return:
"""
for x, y, w, h in rects:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 255, 00), 2)
face = img
face = cv2.resize(face,(224,224))
if Gender.predict(face)==1:
text = "Male"
else:
text = "Female"
cv2.putText(img, text, (x, h), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), lineType=cv2.LINE_AA)
python类FONT_HERSHEY_SIMPLEX的实例源码
def test_image(addr):
target = ['angry','disgust','fear','happy','sad','surprise','neutral']
font = cv2.FONT_HERSHEY_SIMPLEX
im = cv2.imread(addr)
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,scaleFactor=1.1)
for (x, y, w, h) in faces:
cv2.rectangle(im, (x, y), (x+w, y+h), (0, 255, 0), 2,5)
face_crop = im[y:y+h,x:x+w]
face_crop = cv2.resize(face_crop,(48,48))
face_crop = cv2.cvtColor(face_crop, cv2.COLOR_BGR2GRAY)
face_crop = face_crop.astype('float32')/255
face_crop = np.asarray(face_crop)
face_crop = face_crop.reshape(1, 1,face_crop.shape[0],face_crop.shape[1])
result = target[np.argmax(model.predict(face_crop))]
cv2.putText(im,result,(x,y), font, 1, (200,0,0), 3, cv2.LINE_AA)
cv2.imshow('result', im)
cv2.imwrite('result.jpg',im)
cv2.waitKey(0)
def extract_checkerboard_and_draw_corners(self, image, chbrd_size):
image = CvBridge().imgmsg_to_cv2(image, 'mono8')
image_color = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
ret, corners = cv2.findChessboardCorners(image_color, chbrd_size)
if not ret:
cv2.putText(image_color, 'Checkerboard not found', (0, self.res_height - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255))
cv2.drawChessboardCorners(image_color, chbrd_size, corners, ret)
return ret, corners, image_color
def _stampText(image, text, line):
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.55
margin = 5
thickness = 2
color = (255, 255, 255)
size = cv2.getTextSize(text, font, font_scale, thickness)
text_width = size[0][0]
text_height = size[0][1]
line_height = text_height + size[1] + margin
x = image.shape[1] - margin - text_width
y = margin + size[0][1] + line * line_height
cv2.putText(image, text, (x, y), font, font_scale, color, thickness)
def _draw_box(im, box_list, label_list, color=(0,255,0), cdict=None, form='center'):
assert form == 'center' or form == 'diagonal', \
'bounding box format not accepted: {}.'.format(form)
for bbox, label in zip(box_list, label_list):
if form == 'center':
bbox = bbox_transform(bbox)
xmin, ymin, xmax, ymax = [int(b) for b in bbox]
l = label.split(':')[0] # text before "CLASS: (PROB)"
if cdict and l in cdict:
c = cdict[l]
else:
c = color
# draw box
cv2.rectangle(im, (xmin, ymin), (xmax, ymax), c, 1)
# draw label
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(im, label, (xmin, ymax), font, 0.3, c, 1)
def add_text(img, text, text_top, image_scale):
"""
Args:
img (numpy array of shape (width, height, 3): input image
text (str): text to add to image
text_top (int): location of top text to add
image_scale (float): image resize scale
Summary:
Add display text to a frame.
Returns:
Next available location of top text (allows for chaining this function)
"""
cv2.putText(
img=img,
text=text,
org=(0, text_top),
fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=0.15 * image_scale,
color=(255, 255, 255))
return text_top + int(5 * image_scale)
def save_all_detection(im_array, detections, imdb_classes=None, thresh=0.7):
"""
save all detections in one image with result.png
:param im_array: [b=1 c h w] in rgb
:param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
:param imdb_classes: list of names in imdb
:param thresh: threshold for valid detections
:return:
"""
import random
im = image_processing.transform_inverse(im_array, config.PIXEL_MEANS)
im = im[:, :, ::-1].copy() # back to b,g,r
for j in range(1, len(imdb_classes)):
color = (255*random.random(), 255*random.random(), 255*random.random()) # generate a random color
dets = detections[j]
for i in range(dets.shape[0]):
bbox = dets[i, :4]
score = dets[i, -1]
if score > thresh:
cv2.rectangle(im, (int(round(bbox[0])), int(round(bbox[1]))),
(int(round(bbox[2])), int(round(bbox[3]))), color, 2)
cv2.putText(im, '%s'%imdb_classes[j], (bbox[0], bbox[1]),
cv2.FONT_HERSHEY_SIMPLEX, 1.0, color, 2)
cv2.imwrite("result.jpg", im)
def draw_markers(img,markers):
for m in markers:
centroid = np.array(m['centroid'],dtype=np.float32)
origin = np.array(m['verts'][0],dtype=np.float32)
hat = np.array([[[0,0],[0,1],[.5,1.25],[1,1],[1,0]]],dtype=np.float32)
hat = cv2.perspectiveTransform(hat,m_marker_to_screen(m))
if m['id_confidence']>.9:
cv2.polylines(img,np.int0(hat),color = (0,0,255),isClosed=True)
else:
cv2.polylines(img,np.int0(hat),color = (0,255,0),isClosed=True)
# cv2.polylines(img,np.int0(centroid),color = (255,255,int(255*m['id_confidence'])),isClosed=True,thickness=2)
m_str = 'id: {:d}'.format(m['id'])
org = origin.copy()
# cv2.rectangle(img, tuple(np.int0(org+(-5,-13))[0,:]), tuple(np.int0(org+(100,30))[0,:]),color=(0,0,0),thickness=-1)
cv2.putText(img,m_str,tuple(np.int0(org)[0,:]),fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.4, color=(0,0,255))
if 'id_confidence' in m:
m_str = 'idc: {:.3f}'.format(m['id_confidence'])
org += (0, 12)
cv2.putText(img,m_str,tuple(np.int0(org)[0,:]),fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.4, color=(0,0,255))
if 'loc_confidence' in m:
m_str = 'locc: {:.3f}'.format(m['loc_confidence'])
org += (0, 12 )
cv2.putText(img,m_str,tuple(np.int0(org)[0,:]),fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.4, color=(0,0,255))
if 'frames_since_true_detection' in m:
m_str = 'otf: {}'.format(m['frames_since_true_detection'])
org += (0, 12 )
cv2.putText(img,m_str,tuple(np.int0(org)[0,:]),fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.4, color=(0,0,255))
if 'opf_vel' in m:
m_str = 'otf: {}'.format(m['opf_vel'])
org += (0, 12 )
cv2.putText(img,m_str,tuple(np.int0(org)[0,:]),fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.4, color=(0,0,255))
def vis_detections(im, class_name, dets, thresh=0.5):
"""Draw detected bounding boxes."""
inds = np.where(dets[:, -1] >= thresh)[0]
if len(inds) == 0:
return
for i in inds:
bbox = dets[i, :4]
score = dets[i, -1]
#Create Rectangle and Text using OpenCV
#print ('ClassName:', class_name, 'bbox:', bbox, 'score:' ,score)
#Draw the Rectangle
cv2.rectangle(im, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 3)
#Draw the Text
cv2.putText(im, class_name + ' ' + str(score), (bbox[0], bbox[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
#Show Image
#cv2.imshow("Detect Result", im)
def click_and_crop(event, x, y, flags, param):
global bbs, x_upper, id
if event == cv2.EVENT_LBUTTONDOWN:
if x_upper:
bbs.append([x,y,0,0, 0,0,0,0])
else:
bbs[-1][4] = x
bbs[-1][5] = y
elif event == cv2.EVENT_LBUTTONUP:
if x_upper:
bbs[-1][2] = abs(x - bbs[-1][0])
bbs[-1][3] = abs(y - bbs[-1][1])
bbs[-1][0] = min(x, bbs[-1][0])
bbs[-1][1] = min(y, bbs[-1][1])
cv2.rectangle(image, (bbs[-1][0],bbs[-1][1]), (bbs[-1][0]+bbs[-1][2],bbs[-1][1]+bbs[-1][3]), (0,0,255), 2)
#cv2.putText(image, 'Upper %d' % id, (bbs[-1][0],bbs[-1][1]), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0,0,255))
else:
bbs[-1][6] = abs(x - bbs[-1][4])
bbs[-1][7] = abs(y - bbs[-1][5])
bbs[-1][4] = min(x, bbs[-1][4])
bbs[-1][5] = min(y, bbs[-1][5])
cv2.rectangle(image, (bbs[-1][4],bbs[-1][5]), (bbs[-1][4]+bbs[-1][6],bbs[-1][5]+bbs[-1][7]), (0,255,0), 2)
cv2.putText(image, 'Body %d' % id, (bbs[-1][4],bbs[-1][5]), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0,255,0))
cv2.imshow("image", image)
x_upper = not x_upper
def draw_result(out, im_scale, clss, bbox, nms_thresh, conf):
CV_AA = 16
for cls_id in range(1, 21):
_cls = clss[:, cls_id][:, np.newaxis]
_bbx = bbox[:, cls_id * 4: (cls_id + 1) * 4]
dets = np.hstack((_bbx, _cls))
keep = nms(dets, nms_thresh)
dets = dets[keep, :]
inds = np.where(dets[:, -1] >= conf)[0]
for i in inds:
x1, y1, x2, y2 = map(int, dets[i, :4])
cv.rectangle(out, (x1, y1), (x2, y2), (0, 0, 255), 2, CV_AA)
ret, baseline = cv.getTextSize(
CLASSES[cls_id], cv.FONT_HERSHEY_SIMPLEX, 0.8, 1)
cv.rectangle(out, (x1, y2 - ret[1] - baseline),
(x1 + ret[0], y2), (0, 0, 255), -1)
cv.putText(out, CLASSES[cls_id], (x1, y2 - baseline),
cv.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 1, CV_AA)
return out
def draw_rects(img, rects, color):
"""
?????????????
:param img:
:param rects:
:param color:
:return:
"""
for x, y, w, h in rects:
face = img[x:x+w,y:y+h]
face = cv2.resize(face,(224,224))
if gender.predict(face)==1:
text = "Male"
else:
text = "Female"
cv2.rectangle(img, (x, y), (w, h), color, 2)
cv2.putText(img, text, (x, h), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), lineType=cv2.LINE_AA)
Modules.py 文件源码
项目:apparent-age-gender-classification
作者: danielyou0230
项目源码
文件源码
阅读 33
收藏 0
点赞 0
评论 0
def facial_landmark_detection(image, detector, predictor, file):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
img_size = gray.shape
landmark_faces = detector(gray, 1)
faces = list()
area = 0
face_idx = 0
bItr = False
for (idx, landmark_faces) in enumerate(landmark_faces):
shape = predictor(gray, landmark_faces)
shape = shape_to_np(shape)
(x, y, w, h) = rect_to_bb(landmark_faces, img_size, file)
if (w * h) > area:
area = w * h
faces = [x, y, w, h]
bItr = True
#cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
#cv2.putText(image, "Face #{}".format(idx + 1), (x - 10, y - 10), \
# cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
#for (x, y) in shape:
# cv2.circle(image, (x, y), 1, (0, 0, 255), -1)
return bItr, faces
def _draw_boxes_to_image(im, res):
colors = [(86, 0, 240), (173, 225, 61), (54, 137, 255),\
(151, 0, 255), (243, 223, 48), (0, 117, 255),\
(58, 184, 14), (86, 67, 140), (121, 82, 6),\
(174, 29, 128), (115, 154, 81), (86, 255, 234)]
font = cv2.FONT_HERSHEY_SIMPLEX
image = np.copy(im)
cnt = 0
for ind, r in enumerate(res):
if r['dets'] is None: continue
dets = r['dets']
for i in range(0, dets.shape[0]):
(x1, y1, x2, y2, score) = dets[i, :]
cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), colors[ind % len(colors)], 2)
text = '{:s} {:.2f}'.format(r['class'], score)
cv2.putText(image, text, (x1, y1), font, 0.6, colors[ind % len(colors)], 1)
cnt = (cnt + 1)
return image
def _draw_boxes_to_image(im, res):
colors = [(86, 0, 240), (173, 225, 61), (54, 137, 255),\
(151, 0, 255), (243, 223, 48), (0, 117, 255),\
(58, 184, 14), (86, 67, 140), (121, 82, 6),\
(174, 29, 128), (115, 154, 81), (86, 255, 234)]
font = cv2.FONT_HERSHEY_SIMPLEX
image = np.copy(im)
cnt = 0
for ind, r in enumerate(res):
if r['dets'] is None: continue
dets = r['dets']
for i in range(0, dets.shape[0]):
(x1, y1, x2, y2, score) = dets[i, :]
cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), colors[ind % len(colors)], 2)
text = '{:s} {:.2f}'.format(r['class'], score)
cv2.putText(image, text, (x1, y1), font, 0.6, colors[ind % len(colors)], 1)
cnt = (cnt + 1)
return image
def _draw_on_image(img, objs, class_sets_dict):
colors = [(86, 0, 240), (173, 225, 61), (54, 137, 255),\
(151, 0, 255), (243, 223, 48), (0, 117, 255),\
(58, 184, 14), (86, 67, 140), (121, 82, 6),\
(174, 29, 128), (115, 154, 81), (86, 255, 234)]
font = cv2.FONT_HERSHEY_SIMPLEX
for ind, obj in enumerate(objs):
if obj['box'] is None: continue
x1, y1, x2, y2 = obj['box'].astype(int)
cls_id = class_sets_dict[obj['class']]
if obj['class'] == 'dontcare':
cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (255, 0, 0), 1)
continue
cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), colors[cls_id % len(colors)], 1)
text = '{:s}*|'.format(obj['class'][:3]) if obj['difficult'] == 1 else '{:s}|'.format(obj['class'][:3])
text += '{:.1f}|'.format(obj['truncation'])
text += str(obj['occlusion'])
cv2.putText(img, text, (x1-2, y2-2), font, 0.5, (255, 0, 255), 1)
return img
def my_draw_box(im, box_list, label_list, color=(0,255,0), cdict=None, label_placement='bottom'):
assert label_placement == 'bottom' or label_placement == 'top', \
'label_placement format not accepted: {}.'.format(label_placement)
for bbox, label in zip(box_list, label_list):
xmin, ymin, xmax, ymax = [int(b) for b in bbox]
l = label.split(':')[0] # text before "CLASS: (PROB)"
if cdict and l in cdict:
c = cdict[l]
else:
c = color
# draw box
cv2.rectangle(im, (xmin, ymin), (xmax, ymax), c, 1)
# draw label
font = cv2.FONT_HERSHEY_SIMPLEX
if label_placement == 'bottom':
cv2.putText(im, label, (xmin, ymax), font, 0.3, c, 1)
else:
cv2.putText(im, label, (xmin, ymin), font, 0.3, c, 1)
def display_shape():
global shape
if shape == 0:
cv2.putText(obj, 'Off', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
elif shape == 1:
cv2.putText(obj, 'Pencil', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
elif shape == 2:
cv2.putText(obj, 'Brush', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
elif shape == 3:
cv2.putText(obj, 'Eraser', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
elif shape == 4:
cv2.putText(obj, 'Line', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
elif shape == 5:
cv2.putText(obj, 'Rectangle', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
elif shape == 6:
cv2.putText(obj, 'Circle', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
def drawAxis(camera_parameters, markers, frame):
axis = np.float32([[1,0,0], [0,1,0], [0,0,1]]).reshape(-1,3)
mtx, dist = camera_parameters.camera_matrix, camera_parameters.dist_coeff
for marker in markers:
rvec, tvec = marker.rvec, marker.tvec
imgpts, jac = cv2.projectPoints(axis, rvec, tvec, mtx, dist)
corners = marker.corners
corner = tuple(corners[0].ravel())
cv2.line(frame, corner, tuple(imgpts[0].ravel()), (0,0,255), 2)
cv2.line(frame, corner, tuple(imgpts[1].ravel()), (0,255,0), 2)
cv2.line(frame, corner, tuple(imgpts[2].ravel()), (255,0,0), 2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame, 'X', tuple(imgpts[0].ravel()), font, 0.5, (0,0,255), 2, cv2.LINE_AA)
cv2.putText(frame, 'Y', tuple(imgpts[1].ravel()), font, 0.5, (0,255,0), 2, cv2.LINE_AA)
cv2.putText(frame, 'Z', tuple(imgpts[2].ravel()), font, 0.5, (255,0,0), 2, cv2.LINE_AA)
def drawAxis(camera_parameters, markers, frame):
axis = np.float32([[1,0,0], [0,1,0], [0,0,1]]).reshape(-1,3)
mtx, dist = camera_parameters.camera_matrix, camera_parameters.dist_coeff
for marker in markers:
rvec, tvec = marker.rvec, marker.tvec
imgpts, jac = cv2.projectPoints(axis, rvec, tvec, mtx, dist)
corners = marker.corners
corner = tuple(corners[0].ravel())
cv2.line(frame, corner, tuple(imgpts[0].ravel()), (0,0,255), 2)
cv2.line(frame, corner, tuple(imgpts[1].ravel()), (0,255,0), 2)
cv2.line(frame, corner, tuple(imgpts[2].ravel()), (255,0,0), 2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame, 'X', tuple(imgpts[0].ravel()), font, 0.5, (0,0,255), 2, cv2.LINE_AA)
cv2.putText(frame, 'Y', tuple(imgpts[1].ravel()), font, 0.5, (0,255,0), 2, cv2.LINE_AA)
cv2.putText(frame, 'Z', tuple(imgpts[2].ravel()), font, 0.5, (255,0,0), 2, cv2.LINE_AA)
def drawAxis(camera_parameters, markers, frame):
axis = np.float32([[1,0,0], [0,1,0], [0,0,1]]).reshape(-1,3)
mtx, dist = camera_parameters.camera_matrix, camera_parameters.dist_coeff
for marker in markers:
rvec, tvec = marker.rvec, marker.tvec
imgpts, jac = cv2.projectPoints(axis, rvec, tvec, mtx, dist)
corners = marker.corners
corner = tuple(corners[0].ravel())
cv2.line(frame, corner, tuple(imgpts[0].ravel()), (0,0,255), 2)
cv2.line(frame, corner, tuple(imgpts[1].ravel()), (0,255,0), 2)
cv2.line(frame, corner, tuple(imgpts[2].ravel()), (255,0,0), 2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame, 'X', tuple(imgpts[0].ravel()), font, 0.5, (0,0,255), 2, cv2.LINE_AA)
cv2.putText(frame, 'Y', tuple(imgpts[1].ravel()), font, 0.5, (0,255,0), 2, cv2.LINE_AA)
cv2.putText(frame, 'Z', tuple(imgpts[2].ravel()), font, 0.5, (255,0,0), 2, cv2.LINE_AA)
def _renderResultOnImage(self, result, arr):
"""
Draws boxes and text representing each face's emotion.
"""
import operator, cv2
img = cv2.cvtColor(cv2.imdecode(arr, -1), cv2.COLOR_BGR2RGB)
for currFace in result:
faceRectangle = currFace['faceRectangle']
cv2.rectangle(img,(faceRectangle['left'],faceRectangle['top']),
(faceRectangle['left']+faceRectangle['width'], faceRectangle['top'] + faceRectangle['height']),
color = (255,0,0), thickness = 5)
for currFace in result:
faceRectangle = currFace['faceRectangle']
currEmotion = max(iter(currFace['scores'].items()), key=operator.itemgetter(1))[0]
textToWrite = '{0}'.format(currEmotion)
cv2.putText(img, textToWrite, (faceRectangle['left'],faceRectangle['top']-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 1)
return img
def photoRead(filename):
frame = cv2.imread(filename)
FaceArray = getFaceArray(frame)
for r in FaceArray:
img2 = cv2.rectangle(frame, (r[0], r[1]), (r[2], r[3]), (0, 255, 0), 3)
img3 = frame[r[1]:r[3], r[0]:r[2]] # ?????????????
feature = Tools.get_feature(img3)
name = readFace(feature)
font = cv2.FONT_HERSHEY_SIMPLEX
img2 = cv2.putText(img2, name, (r[1], r[3]), font, 1, (255, 255, 255), 2)
cv2.imshow('frame', frame)
cv2.waitKey(0)
def start():
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
FaceArray=getFaceArray(frame)
img2=frame
for r in FaceArray :
img2=cv2.rectangle(frame, (r[0], r[1]), (r[2], r[3]), (0, 255, 0), 3)
img3 = frame[r[1]:r[3], r[0]:r[2]] # ?????????????
feature=Tools.get_feature(img3)
name=readFace(feature)
font=cv2.FONT_HERSHEY_SIMPLEX
img2= cv2.putText(img2,name,(r[1],r[3]), font, 1,(255,255,255),2)
cv2.imshow('frame',img2)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
def renderResultOnImage( result, img ):
"""Display the obtained results onto the input image"""
for currFace in result:
faceRectangle = currFace['faceRectangle']
cv2.rectangle( img,(faceRectangle['left'],faceRectangle['top']),
(faceRectangle['left']+faceRectangle['width'], faceRectangle['top'] + faceRectangle['height']),
color = (255,0,0), thickness = 5 )
for currFace in result:
faceRectangle = currFace['faceRectangle']
currEmotion = max(currFace['scores'].items(), key=operator.itemgetter(1))[0]
textToWrite = "%s" % ( currEmotion )
cv2.putText( img, textToWrite, (faceRectangle['left'],faceRectangle['top']-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 1 )
# img = os.path.expanduser('~/Development/sentiEdu/learning/confusedImgs/4.jpg')
def renderResultOnImage( result, img ):
"""Display the obtained results onto the input image"""
for currFace in result:
faceRectangle = currFace['faceRectangle']
cv2.rectangle( img,(faceRectangle['left'],faceRectangle['top']),
(faceRectangle['left']+faceRectangle['width'], faceRectangle['top'] + faceRectangle['height']),
color = (255,0,0), thickness = 5 )
for currFace in result:
faceRectangle = currFace['faceRectangle']
currEmotion = max(currFace['scores'].items(), key=operator.itemgetter(1))[0]
textToWrite = "%s" % ( currEmotion )
cv2.putText( img, textToWrite, (faceRectangle['left'],faceRectangle['top']-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 1 )
# img = os.path.expanduser('~/Development/sentiEdu/learning/confusedImgs/4.jpg')
def renderResultOnImage( result, img ):
"""Display the obtained results onto the input image"""
for currFace in result:
faceRectangle = currFace['faceRectangle']
cv2.rectangle( img,(faceRectangle['left'],faceRectangle['top']),
(faceRectangle['left']+faceRectangle['width'], faceRectangle['top'] + faceRectangle['height']),
color = (255,0,0), thickness = 5 )
for currFace in result:
faceRectangle = currFace['faceRectangle']
currEmotion = max(currFace['scores'].items(), key=operator.itemgetter(1))[0]
textToWrite = "%s" % ( currEmotion )
cv2.putText( img, textToWrite, (faceRectangle['left'],faceRectangle['top']-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 1 )
# img = os.path.expanduser('~/Development/sentiEdu/learning/confusedImgs/4.jpg')
def vis_detections(im, class_name, dets, thresh=0.5):
"""Draw detected bounding boxes."""
inds = np.where(dets[:, -1] >= thresh)[0]
if len(inds) == 0:
return
l_bboxes = []
for i in inds:
bbox = dets[i, :4]
score = dets[i, -1]
print ('Det: (x_min,y_min,W,H) = ({},{},{},{}), class_name = {:s}, score = {:.3f}').format(
int(bbox[0]),int(bbox[1]),int(bbox[2]-bbox[0]),int(bbox[3]-bbox[1]),class_name,score)
cv2.rectangle(im, (bbox[0], bbox[3]),(bbox[2],bbox[1]), (0,255,0),2)
cv2.putText(im,'{:s}:{:.3f}'.format(class_name, score),
(int(bbox[0]), int(bbox[1]) - 3), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0),2)
l_bboxes.append({'x_min':int(bbox[0]),'y_min':int(bbox[1]),'x_max':bbox[2],'y_max':bbox[3],'cls':class_name,'score':score})
return l_bboxes
def _draw_boxes_to_image(im, res):
colors = [(86, 0, 240), (173, 225, 61), (54, 137, 255),\
(151, 0, 255), (243, 223, 48), (0, 117, 255),\
(58, 184, 14), (86, 67, 140), (121, 82, 6),\
(174, 29, 128), (115, 154, 81), (86, 255, 234)]
font = cv2.FONT_HERSHEY_SIMPLEX
image = np.copy(im)
cnt = 0
for ind, r in enumerate(res):
if r['dets'] is None: continue
dets = r['dets']
for i in range(0, dets.shape[0]):
(x1, y1, x2, y2, score) = dets[i, :]
cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), colors[ind % len(colors)], 2)
text = '{:s} {:.2f}'.format(r['class'], score)
cv2.putText(image, text, (x1, y1), font, 0.6, colors[ind % len(colors)], 1)
cnt = (cnt + 1)
return image
def _draw_on_image(img, objs, class_sets_dict):
colors = [(86, 0, 240), (173, 225, 61), (54, 137, 255),\
(151, 0, 255), (243, 223, 48), (0, 117, 255),\
(58, 184, 14), (86, 67, 140), (121, 82, 6),\
(174, 29, 128), (115, 154, 81), (86, 255, 234)]
font = cv2.FONT_HERSHEY_SIMPLEX
for ind, obj in enumerate(objs):
if obj['box'] is None: continue
x1, y1, x2, y2 = obj['box'].astype(int)
cls_id = class_sets_dict[obj['class']]
if obj['class'] == 'dontcare':
cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (255, 0, 0), 1)
continue
cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), colors[cls_id % len(colors)], 1)
text = '{:s}*|'.format(obj['class'][:3]) if obj['difficult'] == 1 else '{:s}|'.format(obj['class'][:3])
text += '{:.1f}|'.format(obj['truncation'])
text += str(obj['occlusion'])
cv2.putText(img, text, (x1-2, y2-2), font, 0.5, (255, 0, 255), 1)
return img