Shri Jayaram commited on
Commit
bcac4bb
·
1 Parent(s): 96c9e4c

initial commit

Browse files
Files changed (3) hide show
  1. FlowChart.png +0 -0
  2. app.py +326 -0
  3. requirements.txt +9 -0
FlowChart.png ADDED
app.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+ import io
4
+ import cv2
5
+ import numpy as np
6
+ import matplotlib.pyplot as plt
7
+ import io as BytesIO
8
+ from rembg import remove
9
+ from streamlit_cropper import st_cropper
10
+ import mediapipe as mp
11
+ from scipy.spatial import distance as dist
12
+
13
+ ring_size_dict = {
14
+ 14.0: 3,
15
+ 14.4: 3.5,
16
+ 14.8: 4,
17
+ 15.2: 4.5,
18
+ 15.6: 5,
19
+ 16.0: 5.5,
20
+ 16.45: 6,
21
+ 16.9: 6.5,
22
+ 17.3: 7,
23
+ 17.7: 7.5,
24
+ 18.2: 8,
25
+ 18.6: 8.5,
26
+ 19.0: 9,
27
+ 19.4: 9.5,
28
+ 19.8: 10,
29
+ 20.2: 10.5,
30
+ 20.6: 11,
31
+ 21.0: 11.5,
32
+ 21.4: 12,
33
+ 21.8: 12.5,
34
+ 22.2: 13,
35
+ 22.6: 13.5
36
+ }
37
+
38
+ def calculate_pixel_per_metric(image, known_length_of_line=50): # Line length in mm
39
+ grayed = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
40
+
41
+ pixel_per_metric = None
42
+
43
+ edges = cv2.Canny(grayed, 0, 150, apertureSize=3)
44
+
45
+ lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=100, minLineLength=100, maxLineGap=50)
46
+ if lines is not None:
47
+ longest_line = None
48
+ max_length = 0
49
+
50
+ for line in lines:
51
+ x1, y1, x2, y2 = line[0]
52
+ length = np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
53
+
54
+ if length > max_length:
55
+ max_length = length
56
+ longest_line = (x1, y1, x2, y2)
57
+
58
+ if longest_line is not None:
59
+ x1, y1, x2, y2 = longest_line
60
+ pixel_per_metric = max_length / known_length_of_line
61
+
62
+ # Optionally draw the detected line on the image (you can remove this if not needed)
63
+ cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
64
+ cv2.circle(image, (x1, y1), 5, (0, 0, 255), -1)
65
+ cv2.circle(image, (x2, y2), 5, (255, 0, 0), -1)
66
+
67
+ return pixel_per_metric, max_length, image # Returning None for mm_per_pixel as it is not applicable here ok gud
68
+
69
+ def process_image(image):
70
+ return remove(image)
71
+
72
+ def calculate_pip_width(image, original_img, pixel_per_metric):
73
+ def calSize(xA, yA, xB, yB, color_circle, color_line, img):
74
+ d = dist.euclidean((xA, yA), (xB, yB))
75
+ cv2.circle(img, (int(xA), int(yA)), 5, color_circle, -1)
76
+ cv2.circle(img, (int(xB), int(yB)), 5, color_circle, -1)
77
+ cv2.line(img, (int(xA), int(yA)), (int(xB), int(yB)), color_line, 2)
78
+ d_mm = d / pixel_per_metric
79
+ d_mm = d_mm - 1.5
80
+ cv2.putText(img, "{:.1f}".format(d_mm), (int(xA - 15), int(yA - 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2)
81
+ print(d_mm)
82
+ return d_mm
83
+
84
+ def process_point(point, cnt, m1, b):
85
+ x1, x2 = point[0], point[0]
86
+ y1 = m1 * x1 + b
87
+ y2 = m1 * x2 + b
88
+
89
+ result = 1.0
90
+ while result > 0:
91
+ result = cv2.pointPolygonTest(cnt, (x1, y1), False)
92
+ x1 += 1
93
+ y1 = m1 * x1 + b
94
+ x1 -= 1
95
+
96
+ result = 1.0
97
+ while result > 0:
98
+ result = cv2.pointPolygonTest(cnt, (x2, y2), False)
99
+ x2 -= 1
100
+ y2 = m1 * x2 + b
101
+ x2 += 1
102
+
103
+ return x1, y1, x2, y2
104
+
105
+ og_img = original_img.copy()
106
+ imgH, imgW, _ = image.shape
107
+ imgcpy = image.copy()
108
+ image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
109
+ _, binary_image = cv2.threshold(image_gray, 1, 255, cv2.THRESH_BINARY)
110
+ contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
111
+ contour_image = np.zeros_like(image_gray)
112
+ cv2.drawContours(contour_image, contours, -1, (255), thickness=cv2.FILLED)
113
+ cv2.drawContours(imgcpy, contours, -1, (0, 255, 0), 2)
114
+ # print("length : ",len(contours))
115
+
116
+ marked_img = image.copy()
117
+
118
+ if len(contours) > 0:
119
+ cnt = max(contours, key=cv2.contourArea)
120
+ frame2 = cv2.cvtColor(og_img, cv2.COLOR_BGR2RGB)
121
+ handsLM = mp.solutions.hands.Hands(max_num_hands=1, min_detection_confidence=0.8, min_tracking_confidence=0.8)
122
+ pr = handsLM.process(frame2)
123
+ print(pr.multi_hand_landmarks)
124
+ if pr.multi_hand_landmarks:
125
+ for hand_landmarks in pr.multi_hand_landmarks:
126
+ lmlist = []
127
+ for id, landMark in enumerate(hand_landmarks.landmark):
128
+ xPos, yPos = int(landMark.x * imgW), int(landMark.y * imgH)
129
+ lmlist.append([id, xPos, yPos])
130
+
131
+ if len(lmlist) != 0:
132
+ pip_joint = [lmlist[14][1], lmlist[14][2]]
133
+ mcp_joint = [lmlist[13][1], lmlist[13][2]]
134
+
135
+ midpoint_x = (pip_joint[0] + mcp_joint[0]) / 2
136
+ midpoint_y = (pip_joint[1] + mcp_joint[1]) / 2
137
+ midpoint = [midpoint_x, midpoint_y]
138
+
139
+ m2 = (pip_joint[1] - mcp_joint[1]) / (pip_joint[0] - mcp_joint[0])
140
+ m1 = -1 / m2
141
+ b = pip_joint[1] - m1 * pip_joint[0]
142
+
143
+ #pip_joint
144
+ x1_pip, y1_pip, x2_pip, y2_pip = process_point(pip_joint, cnt, m1, b)
145
+
146
+ m2 = (midpoint_y - mcp_joint[1]) / (midpoint_x - mcp_joint[0])
147
+ m1 = -1 / m2
148
+ b = midpoint_y - m1 * midpoint_x
149
+
150
+ #midpoint
151
+ x1_mid, y1_mid, x2_mid, y2_mid = process_point(midpoint, cnt, m1, b)
152
+
153
+ d_mm_pip = calSize(x1_pip, y1_pip, x2_pip, y2_pip, (255, 0, 0), (255, 0, 255), original_img)
154
+ d_mm_mid = calSize(x1_mid, y1_mid, x2_mid, y2_mid, (0, 255, 0), (0, 0, 255), original_img)
155
+
156
+ largest_d_mm = max(int(d_mm_mid),int(d_mm_pip))
157
+ return original_img, largest_d_mm, imgcpy, marked_img
158
+
159
+ def mark_hand_landmarks(image_path):
160
+
161
+ mp_hands = mp.solutions.hands
162
+ hands = mp_hands.Hands()
163
+ mp_draw = mp.solutions.drawing_utils
164
+
165
+ img = image_path
166
+ img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
167
+
168
+ results = hands.process(img_rgb)
169
+
170
+ if results.multi_hand_landmarks:
171
+ for hand_landmarks in results.multi_hand_landmarks:
172
+ mp_draw.draw_landmarks(img, hand_landmarks, mp_hands.HAND_CONNECTIONS)
173
+
174
+ mcp = hand_landmarks.landmark[13]
175
+ pip = hand_landmarks.landmark[14]
176
+
177
+ img_height, img_width, _ = img.shape
178
+
179
+ mcp_x, mcp_y = int(mcp.x * img_width), int(mcp.y * img_height)
180
+ pip_x, pip_y = int(pip.x * img_width), int(pip.y * img_height)
181
+
182
+ cv2.circle(img, (mcp_x, mcp_y), 10, (255, 0, 0), -1)
183
+ cv2.circle(img, (pip_x, pip_y), 10, (255, 0, 0), -1)
184
+
185
+ return img
186
+
187
+ def show_resized_image(images, titles, scale=0.5):
188
+ num_images = len(images)
189
+
190
+ fig, axes = plt.subplots(2, 3, figsize=(17, 13))
191
+ axes = axes.flatten()
192
+
193
+ for ax in axes[num_images:]:
194
+ ax.axis('off')
195
+
196
+ for ax, img, title in zip(axes, images, titles):
197
+ resized_image = cv2.resize(img, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR)
198
+ ax.imshow(cv2.cvtColor(resized_image, cv2.COLOR_BGR2RGB))
199
+ ax.set_title(title)
200
+ ax.axis('off')
201
+
202
+ plt.tight_layout()
203
+ img_stream = BytesIO.BytesIO()
204
+ plt.savefig(img_stream, format='png')
205
+ img_stream.seek(0)
206
+ plt.close(fig)
207
+ return img_stream
208
+
209
+ def get_ring_size(mm_value):
210
+ if mm_value in ring_size_dict:
211
+ return ring_size_dict[mm_value]
212
+ else:
213
+ closest_mm = min(ring_size_dict.keys(), key=lambda x: abs(x - mm_value))
214
+ return ring_size_dict[closest_mm]
215
+
216
+ st.set_page_config(layout="wide", page_title="Ring Size Measurement")
217
+ st.write("## Determine Your Ring Size")
218
+ st.write(
219
+ "📏 Upload an image of your hand to measure the finger width and determine your ring size. The measurement will be displayed along with a visual breakdown of the image processing flow."
220
+ )
221
+ st.sidebar.write("## Upload :gear:")
222
+ #~~
223
+ st.write("### Workflow Overview")
224
+ st.image("FlowChart.png", caption="Workflow Overview", use_column_width=True)
225
+
226
+ st.write("### Detailed Workflow")
227
+ st.write("1. **Hough Circle Transform:** The Hough Circle Transform is a technique used to detect circles in an image. It works by transforming the image into a parameter space, identifying circles based on their radius and center coordinates. This method is effective for locating circular objects, such as a coin, within the image.")
228
+ st.write("2. **Pixel Per Metric Ratio:** The Pixel Per Metric Ratio is used to convert pixel measurements into real-world units. By comparing the pixel length obtained from image analysis (i.e., Hough Circle) with the known real-world measurement of the reference object (coin), we get the ratio. This ratio then allows us to accurately scale and size estimation of objects within the image.")
229
+ st.write("3. **Background Removal:** Removing the background first ensures that only the relevant subject is highlighted. We start by converting the image to grayscale and applying thresholding to distinguish the subject from the background. Erosion and dilation then clean up the image, improving the detection of specific features like individual fingers.")
230
+ st.write("4. **Contour Detection:** We use Contour Detection to find the largest contour, which allows us to outline or draw a boundary around the subject (i.e., hand). This highlights the object's shape and edges, improving the precision of the subject.")
231
+ st.write("5. **Finding Hand Landmarks:** This involves using the MediaPipe library to identify key points on the hand, such as the PIP (Proximal Interphalangeal) and MCP (Metacarpophalangeal) joints of the ring finger. This enables precise tracking and analysis of finger positions and movements.")
232
+ st.write("6. **Determining Finger Width:** Here we use the slope formula `[y = mx + b]` with PIP and MCP points to measure the finger's width. We project outward perpendicularly from the PIP point towards the MCP point, then apply a point polygon test to accurately determine the pixel width of the finger.")
233
+ st.write("7. **Predicting Ring Size:** Predicting Ring Size involves calculating the finger’s diameter using the Pixel Per Metric Ratio and the largest width measurement at the PIP or MCP joint. This diameter is then used to predict the appropriate ring size.")
234
+ #~~
235
+
236
+ MAX_FILE_SIZE = 5 * 1024 * 1024 # 5MB
237
+
238
+ def process_image_and_get_results(upload):
239
+ image = Image.open(upload)
240
+ # image = cv2.imread(upload)
241
+ image_np = np.array(image)
242
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
243
+ original_img = image_np.copy()
244
+ og_img1 = image_np.copy()
245
+ og_img2 = image_np.copy()
246
+ img_1 = image_np.copy()
247
+ hand_lms = mark_hand_landmarks(img_1)
248
+
249
+ #++++ logic added for getting the roi from user
250
+ st.header("Select ROI for Pixel Measurement")
251
+ st.write("Make sure the line is **Thick** and **Dark** in color.")
252
+ colm_roi,colm_text = st.columns([3,1])
253
+ with colm_roi:
254
+ rect = st_cropper(
255
+ image,
256
+ realtime_update=True,
257
+ box_color='#0000FF',
258
+ aspect_ratio=(16, 9),
259
+ return_type="box",
260
+ stroke_width=3
261
+ )
262
+
263
+ # Extract cropped image
264
+ if rect:
265
+ left, top, width, height = tuple(map(int, rect.values()))
266
+ cropped_image = image_np[top:top + height, left:left + width]
267
+ else:
268
+ st.warning("Please select a region of interest.")
269
+ return None # Or handle as appropriate
270
+ #++++
271
+ pixel_per_metric, max_length, image_with_coin_info = calculate_pixel_per_metric(cropped_image)
272
+ with colm_text:
273
+ st.write(f"""
274
+ Length of Line in Real : `50 mm (5 cm)`
275
+ Length of Line in Pixels : `{max_length:.2f} px`
276
+ Pixel per Metric : `{pixel_per_metric:.2f} px/mm`"""
277
+ )
278
+ processed_image = process_image(og_img1)
279
+ image_with_pip_width, width_mm, contour_image, pip_mark_img = calculate_pip_width(processed_image, original_img, pixel_per_metric)
280
+
281
+ ring_size = get_ring_size(width_mm)
282
+ return {
283
+ "processed_image": image_with_pip_width,
284
+ "original_image": og_img2,
285
+ "hand_lm_marked_image": hand_lms,
286
+ "image_with_coin_info": image_with_coin_info,
287
+ "contour_image": contour_image,
288
+ "width_mm": width_mm,
289
+ "ring_size": ring_size
290
+ }
291
+
292
+ def show_how_it_works(processed_image):
293
+ st.write("## How It Works")
294
+ st.write("Here's a step-by-step breakdown of how your image is processed to determine your ring size:")
295
+ st.image(processed_image, caption="Image Processing Flow", use_column_width=True)
296
+
297
+ col1, col2 = st.columns(2)
298
+ my_upload = st.sidebar.file_uploader("Upload an image", type=["png", "jpg", "jpeg"])
299
+
300
+ if my_upload is not None:
301
+ if my_upload.size > MAX_FILE_SIZE:
302
+ st.error("The uploaded file is too large. Please upload an image smaller than 5MB.")
303
+ else:
304
+
305
+ results = process_image_and_get_results(my_upload)
306
+ st.write("## Image Processing Flow")
307
+
308
+ col1.write("Uploaded Image :camera:")
309
+ col1.image(cv2.cvtColor(results["original_image"], cv2.COLOR_BGR2RGB), caption="Uploaded Image")
310
+
311
+ col2.write("Processed Image :wrench:")
312
+ col2.image(cv2.cvtColor(results["processed_image"], cv2.COLOR_BGR2RGB), caption="Processed Image with PIP Width")
313
+
314
+ st.write(f"📏 The width of your finger is {results['width_mm']:.2f} mm, and the estimated ring size is {results['ring_size']:.1f}.")
315
+
316
+ if st.button("How it Works"):
317
+ st.write("## How It Works")
318
+ st.write("Here's a step-by-step breakdown of how your image is processed to determine your ring size:")
319
+ img_stream = show_resized_image(
320
+ [results["original_image"], results["image_with_coin_info"], results["contour_image"], results["hand_lm_marked_image"], results["processed_image"]],
321
+ ['Original Image', 'Image with Coin Info', 'Contour Boundary Image', 'Hand Landmarks', 'Ring Finger Width'],
322
+ scale=0.5
323
+ )
324
+ st.image(img_stream, caption="Processing Flow", use_column_width=True)
325
+ else:
326
+ st.info("Please upload an image to get started.")
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ Pillow
3
+ opencv-python
4
+ numpy
5
+ matplotlib
6
+ rembg
7
+ streamlit-cropper
8
+ mediapipe
9
+ scipy