CoolFace
Apppublic

DShrimp/PoseMaker

sourceHugging Facecreativeml-openrail-mupdated 4y agoView on Hugging Face
1likes
util.py199 linesDownload Raw Back to src
1import numpy as np2import math3import cv24import matplotlib5from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas6from matplotlib.figure import Figure7import numpy as np8import matplotlib.pyplot as plt9import cv210 11 12def padRightDownCorner(img, stride, padValue):13    h = img.shape[0]14    w = img.shape[1]15 16    pad = 4 * [None]17    pad[0] = 0 # up18    pad[1] = 0 # left19    pad[2] = 0 if (h % stride == 0) else stride - (h % stride) # down20    pad[3] = 0 if (w % stride == 0) else stride - (w % stride) # right21 22    img_padded = img23    pad_up = np.tile(img_padded[0:1, :, :]*0 + padValue, (pad[0], 1, 1))24    img_padded = np.concatenate((pad_up, img_padded), axis=0)25    pad_left = np.tile(img_padded[:, 0:1, :]*0 + padValue, (1, pad[1], 1))26    img_padded = np.concatenate((pad_left, img_padded), axis=1)27    pad_down = np.tile(img_padded[-2:-1, :, :]*0 + padValue, (pad[2], 1, 1))28    img_padded = np.concatenate((img_padded, pad_down), axis=0)29    pad_right = np.tile(img_padded[:, -2:-1, :]*0 + padValue, (1, pad[3], 1))30    img_padded = np.concatenate((img_padded, pad_right), axis=1)31 32    return img_padded, pad33 34# transfer caffe model to pytorch which will match the layer name35def transfer(model, model_weights):36    transfered_model_weights = {}37    for weights_name in model.state_dict().keys():38        transfered_model_weights[weights_name] = model_weights['.'.join(weights_name.split('.')[1:])]39    return transfered_model_weights40 41# draw the body keypoint and lims42def draw_bodypose(canvas, candidate, subset):43    stickwidth = 444    limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \45               [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \46               [1, 16], [16, 18], [3, 17], [6, 18]]47 48    colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \49              [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \50              [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]51    for i in range(18):52        for n in range(len(subset)):53            index = int(subset[n][i])54            if index == -1:55                continue56            x, y = candidate[index][0:2]57            cv2.circle(canvas, (int(x), int(y)), 4, colors[i], thickness=-1)58    for i in range(17):59        for n in range(len(subset)):60            index = subset[n][np.array(limbSeq[i]) - 1]61            if -1 in index:62                continue63            cur_canvas = canvas.copy()64            Y = candidate[index.astype(int), 0]65            X = candidate[index.astype(int), 1]66            mX = np.mean(X)67            mY = np.mean(Y)68            length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.569            angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))70            polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)71            cv2.fillConvexPoly(cur_canvas, polygon, colors[i])72            canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)73    # plt.imsave("preview.jpg", canvas[:, :, [2, 1, 0]])74    # plt.imshow(canvas[:, :, [2, 1, 0]])75    return canvas76 77def draw_handpose(canvas, all_hand_peaks, show_number=False):78    edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], \79             [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]80    fig = Figure(figsize=plt.figaspect(canvas))81 82    fig.subplots_adjust(0, 0, 1, 1)83    fig.subplots_adjust(bottom=0, top=1, left=0, right=1)84    bg = FigureCanvas(fig)85    ax = fig.subplots()86    ax.axis('off')87    ax.imshow(canvas)88 89    width, height = ax.figure.get_size_inches() * ax.figure.get_dpi()90 91    for peaks in all_hand_peaks:92        for ie, e in enumerate(edges):93            if np.sum(np.all(peaks[e], axis=1)==0)==0:94                x1, y1 = peaks[e[0]]95                x2, y2 = peaks[e[1]]96                ax.plot([x1, x2], [y1, y2], color=matplotlib.colors.hsv_to_rgb([ie/float(len(edges)), 1.0, 1.0]))97 98        for i, keyponit in enumerate(peaks):99            x, y = keyponit100            ax.plot(x, y, 'r.')101            if show_number:102                ax.text(x, y, str(i))103    bg.draw()104    canvas = np.fromstring(bg.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3)105    return canvas106 107# image drawed by opencv is not good.108def draw_handpose_by_opencv(canvas, peaks, show_number=False):109    edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], \110             [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]111    # cv2.rectangle(canvas, (x, y), (x+w, y+w), (0, 255, 0), 2, lineType=cv2.LINE_AA)112    # cv2.putText(canvas, 'left' if is_left else 'right', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)113    for ie, e in enumerate(edges):114        if np.sum(np.all(peaks[e], axis=1)==0)==0:115            x1, y1 = peaks[e[0]]116            x2, y2 = peaks[e[1]]117            cv2.line(canvas, (x1, y1), (x2, y2), matplotlib.colors.hsv_to_rgb([ie/float(len(edges)), 1.0, 1.0])*255, thickness=2)118 119    for i, keyponit in enumerate(peaks):120        x, y = keyponit121        cv2.circle(canvas, (x, y), 4, (0, 0, 255), thickness=-1)122        if show_number:123            cv2.putText(canvas, str(i), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 0, 0), lineType=cv2.LINE_AA)124    return canvas125 126# detect hand according to body pose keypoints127# please refer to https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/src/openpose/hand/handDetector.cpp128def handDetect(candidate, subset, oriImg):129    # right hand: wrist 4, elbow 3, shoulder 2130    # left hand: wrist 7, elbow 6, shoulder 5131    ratioWristElbow = 0.33132    detect_result = []133    image_height, image_width = oriImg.shape[0:2]134    for person in subset.astype(int):135        # if any of three not detected136        has_left = np.sum(person[[5, 6, 7]] == -1) == 0137        has_right = np.sum(person[[2, 3, 4]] == -1) == 0138        if not (has_left or has_right):139            continue140        hands = []141        #left hand142        if has_left:143            left_shoulder_index, left_elbow_index, left_wrist_index = person[[5, 6, 7]]144            x1, y1 = candidate[left_shoulder_index][:2]145            x2, y2 = candidate[left_elbow_index][:2]146            x3, y3 = candidate[left_wrist_index][:2]147            hands.append([x1, y1, x2, y2, x3, y3, True])148        # right hand149        if has_right:150            right_shoulder_index, right_elbow_index, right_wrist_index = person[[2, 3, 4]]151            x1, y1 = candidate[right_shoulder_index][:2]152            x2, y2 = candidate[right_elbow_index][:2]153            x3, y3 = candidate[right_wrist_index][:2]154            hands.append([x1, y1, x2, y2, x3, y3, False])155 156        for x1, y1, x2, y2, x3, y3, is_left in hands:157            # pos_hand = pos_wrist + ratio * (pos_wrist - pos_elbox) = (1 + ratio) * pos_wrist - ratio * pos_elbox158            # handRectangle.x = posePtr[wrist*3] + ratioWristElbow * (posePtr[wrist*3] - posePtr[elbow*3]);159            # handRectangle.y = posePtr[wrist*3+1] + ratioWristElbow * (posePtr[wrist*3+1] - posePtr[elbow*3+1]);160            # const auto distanceWristElbow = getDistance(poseKeypoints, person, wrist, elbow);161            # const auto distanceElbowShoulder = getDistance(poseKeypoints, person, elbow, shoulder);162            # handRectangle.width = 1.5f * fastMax(distanceWristElbow, 0.9f * distanceElbowShoulder);163            x = x3 + ratioWristElbow * (x3 - x2)164            y = y3 + ratioWristElbow * (y3 - y2)165            distanceWristElbow = math.sqrt((x3 - x2) ** 2 + (y3 - y2) ** 2)166            distanceElbowShoulder = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)167            width = 1.5 * max(distanceWristElbow, 0.9 * distanceElbowShoulder)168            # x-y refers to the center --> offset to topLeft point169            # handRectangle.x -= handRectangle.width / 2.f;170            # handRectangle.y -= handRectangle.height / 2.f;171            x -= width / 2172            y -= width / 2  # width = height173            # overflow the image174            if x < 0: x = 0175            if y < 0: y = 0176            width1 = width177            width2 = width178            if x + width > image_width: width1 = image_width - x179            if y + width > image_height: width2 = image_height - y180            width = min(width1, width2)181            # the max hand box value is 20 pixels182            if width >= 20:183                detect_result.append([int(x), int(y), int(width), is_left])184 185    '''186    return value: [[x, y, w, True if left hand else False]].187    width=height since the network require squared input.188    x, y is the coordinate of top left 189    '''190    return detect_result191 192# get max index of 2d array193def npmax(array):194    arrayindex = array.argmax(1)195    arrayvalue = array.max(1)196    i = arrayvalue.argmax()197    j = arrayindex[i]198    return i, j199