File size: 7,547 Bytes
43dd17a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94c4b5d
43dd17a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e3c5f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f3a09d
4e3c5f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43dd17a
 
 
 
 
 
 
 
74cfe76
e0808f1
 
43dd17a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import cv2
import time
import os
import mediapipe as mp
import gradio as gr
from threading import Thread
#from cvzone.HandTrackingModule import HandDetector
example_flag = False

class handDetector():
    def __init__(self, mode=True, modelComplexity=1, maxHands=2, detectionCon=0.5, trackCon=0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.detectionCon = detectionCon
        self.modelComplex = modelComplexity
        self.trackCon = trackCon
        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands,self.modelComplex,self.detectionCon, self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils

    def findHands(self, img, draw=True,flipType=True):
        """
        Finds hands in a BGR image.
        :param img: Image to find the hands in.
        :param draw: Flag to draw the output on the image.
        :return: Image with or without drawings
        """
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        #cv2.imshow('test',imgRGB)
        self.results = self.hands.process(imgRGB)
        allHands = []
        h, w, c = img.shape
        if self.results.multi_hand_landmarks:
            for handType, handLms in zip(self.results.multi_handedness, self.results.multi_hand_landmarks):
                myHand = {}
                ## lmList
                mylmList = []
                xList = []
                yList = []
                for id, lm in enumerate(handLms.landmark):
                    px, py, pz = int(lm.x * w), int(lm.y * h), int(lm.z * w)
                    mylmList.append([px, py, pz])
                    xList.append(px)
                    yList.append(py)

                ## bbox
                xmin, xmax = min(xList), max(xList)
                ymin, ymax = min(yList), max(yList)
                boxW, boxH = xmax - xmin, ymax - ymin
                bbox = xmin, ymin, boxW, boxH
                cx, cy = bbox[0] + (bbox[2] // 2), \
                         bbox[1] + (bbox[3] // 2)

                myHand["lmList"] = mylmList
                myHand["bbox"] = bbox
                myHand["center"] = (cx, cy)

                if flipType:
                    if handType.classification[0].label == "Right":
                        myHand["type"] = "Left"
                    else:
                        myHand["type"] = "Right"
                else:
                    myHand["type"] = handType.classification[0].label
                allHands.append(myHand)

                ## draw
                if draw:
                    self.mpDraw.draw_landmarks(img, handLms,
                                               self.mpHands.HAND_CONNECTIONS)
                    cv2.rectangle(img, (bbox[0] - 20, bbox[1] - 20),
                                  (bbox[0] + bbox[2] + 20, bbox[1] + bbox[3] + 20),
                                  (255, 0, 255), 2)
                    #cv2.putText(img, myHand["type"], (bbox[0] - 30, bbox[1] - 30), cv2.FONT_HERSHEY_PLAIN,2, (255, 0, 255), 2)
        if draw:
            return allHands, img
        else:
            return allHands
    def findPosition(self, img, handNo=0, draw=True,flipType=False):

        lmList = []
        if self.results.multi_hand_landmarks:
            myHand = self.results.multi_hand_landmarks[handNo]
            for id, lm in enumerate(myHand.landmark):
                # print(id, lm)
                h, w, c = img.shape
                cx, cy = int(lm.x * w), int(lm.y * h)
                # print(id, cx, cy)
                lmList.append([id, cx, cy])
                if draw:
                    cv2.circle(img, (cx, cy), 15, (255, 0, 255), cv2.FILLED)
        return lmList




def set_example_image(example: list) -> dict:
    return gr.inputs.Image.update(value=example[0])


def count(im):
  folderPath = "Count"
  myList = os.listdir(folderPath)
  overlayList = []
  for imPath in sorted(myList):
      image = cv2.imread(f'{folderPath}/{imPath}')
      # print(f'{folderPath}/{imPath}')
      overlayList.append(image)

  #print(len(overlayList))
  tipIds = [4, 8, 12, 16, 20]
  detector = handDetector(detectionCon=0.75)

  #img = cv2.imread('test.jpg')
  allhands,img = detector.findHands(cv2.flip(im[:,:,::-1], 1))
  cv2.imwrite('test3.png',img)
  
  lmList = detector.findPosition(img, draw=False,)
  # print(lmList)

  if len(lmList) != 0:
      fingers = []

      # Thumb
      if lmList[tipIds[0]][1] > lmList[tipIds[0] - 1][1]:
          fingers.append(1)
      else:
          fingers.append(0)

      # 4 Fingers
      for id in range(1, 5):
          if lmList[tipIds[id]][2] < lmList[tipIds[id] - 2][2]:
              fingers.append(1)
          else:
              fingers.append(0)

      # print(fingers)
      totalFingers = fingers.count(1)
      #print(totalFingers)
      text = f"Total finger count is {totalFingers}!"

      h, w, c = overlayList[totalFingers - 1].shape
      img = cv2.flip(img,1)
      img[0:h, 0:w] = overlayList[totalFingers - 1]
      

      cv2.rectangle(img, (20, 225), (170, 425), (0, 255, 0), cv2.FILLED)
      cv2.putText(img, str(totalFingers), (45, 375), cv2.FONT_HERSHEY_PLAIN,
                  10, (255, 0, 0), 25)
      return img[:,:,::-1]
  else:
      return cv2.flip(img[:,:,::-1],1)

css = """
.gr-button-lg {
    z-index: 14;
    width: 113px;
    height: 30px;
    left: 0px;
    top: 0px;
    padding: 0px;
    cursor: pointer !important; 
    background: none rgb(17, 20, 45) !important;
    border: none !important;
    text-align: center !important;
    font-size: 14px !important;
    font-weight: 500 !important;
    color: rgb(255, 255, 255) !important;
    line-height: 1 !important;
    border-radius: 6px !important;
    transition: box-shadow 200ms ease 0s, background 200ms ease 0s !important;
    box-shadow: none !important;
}
.gr-button-lg:hover{
    z-index: 14;
    width: 113px;
    height: 30px;
    left: 0px;
    top: 0px;
    padding: 0px;
    cursor: pointer !important; 
    background: none rgb(66, 133, 244) !important;
    border: none !important;
    text-align: center !important;
    font-size: 14px !important;
    font-weight: 500 !important;
    color: rgb(255, 255, 255) !important;
    line-height: 1 !important;
    border-radius: 6px !important;
    transition: box-shadow 200ms ease 0s, background 200ms ease 0s !important;
    box-shadow: rgb(0 0 0 / 23%) 0px 1px 7px 0px !important;
}

footer {display:none !important} 
.output-markdown{display:none !important} 
#out_image {height: 22rem !important;}

"""

with gr.Blocks(title="Right Hand Finger Counting | Data Science Dojo", css=css) as demo:
  with gr.Tabs():
    with gr.TabItem('Upload'):
      with gr.Row():
        with gr.Column():
          img_input = gr.Image(shape=(640,480))
          image_button = gr.Button("Submit")

        with gr.Column():
          output = gr.Image(shape=(640,480), elem_id="out_image")
      with gr.Row():
          example_images = gr.Dataset(components=[img_input],samples=[["ex2.jpg"]])

    with gr.TabItem('Webcam'):
      with gr.Row():
        with gr.Column():
          img_input2 = gr.Webcam()
          image_button2 = gr.Button("Submit")

        with gr.Column():
          output2 = gr.outputs.Image()

    image_button.click(fn=count,
        inputs = img_input,
        outputs = output)        
    image_button2.click(fn=count,
        inputs = img_input2,
        outputs = output2)
    example_images.click(fn=set_example_image,inputs=[example_images],outputs=[img_input])

 
demo.launch(debug=True)