lukeafullard commited on
Commit
936beb5
·
verified ·
1 Parent(s): cf49f1b

Upload cell_squashing_tracker.py

Browse files
Files changed (1) hide show
  1. cell_squashing_tracker.py +323 -0
cell_squashing_tracker.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Luke Fullard: 16 June 2024
4
+ Script to track an object of interest in a video
5
+ """
6
+
7
+ import streamlit as st
8
+ import cv2
9
+ import numpy as np
10
+ from PIL import Image
11
+ import tempfile
12
+ import pandas as pd
13
+ import os
14
+ from io import BytesIO
15
+ import base64
16
+ from skimage import filters
17
+ ###############################################################################
18
+ ###############################################################################
19
+ ###############################################################################
20
+ # Function to apply image adjustments with new options
21
+ def apply_adjustments(frame, grayscale, contrast, blur, edges, sharpen_amount, subtract_background, lower_threshold, upper_threshold, binarize, binarize_threshold):
22
+ if grayscale:
23
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
24
+ if contrast > 1.0:
25
+ # Clip the values to avoid wrapping around
26
+ frame = np.clip(contrast * frame, 0, 255).astype(np.uint8)
27
+ if blur > 0:
28
+ frame = cv2.GaussianBlur(frame, (blur, blur), 0)
29
+ if edges:
30
+ frame = cv2.Canny(frame, lower_threshold, upper_threshold)
31
+
32
+ # Sharpening
33
+ if sharpen_amount > 0:
34
+ frame = filters.unsharp_mask(frame, radius=1, amount=sharpen_amount)
35
+ frame = (frame * 255).astype(np.uint8) # Convert back to uint8
36
+
37
+ # Background Subtraction
38
+ if subtract_background:
39
+ # Initialize the background subtractor
40
+ fgbg = cv2.createBackgroundSubtractorMOG2()
41
+ frame = fgbg.apply(frame)
42
+
43
+ if binarize:
44
+ _, frame = cv2.threshold(frame, binarize_threshold, 255, cv2.THRESH_BINARY)
45
+
46
+ return frame
47
+
48
+ ###############################################################################
49
+ ###############################################################################
50
+ ###############################################################################
51
+ def part_one():
52
+ st.subheader('Part one: upload your video file')
53
+ with st.expander('Instructions #1'):
54
+ st.write('Please choose a file to upload. At present only the following formats are supported: "mp4", "avi", "mov", "mkv"')
55
+ uploaded_file = st.file_uploader("Choose a video file", type=["mp4", "avi", "mov", "mkv"])
56
+ return uploaded_file
57
+
58
+ ###############################################################################
59
+ ###############################################################################
60
+ ###############################################################################
61
+ def part_two(uploaded_file):
62
+ st.subheader('Part two: adjust image and select region of interest')
63
+ with st.expander('Instructions #2'):
64
+ st.write('''
65
+ Part two is a two step process:
66
+
67
+ a) Use the Image adjustments in the left hand side toolbar to modify the image until suitable for tracking analysis. In practice, I have found the "Binarize" tool to be the most useful for tracking. You can use the frame number selector just above the image to see how the image adjustment affects the other frames in the video sequence.
68
+
69
+ b) Set the region of interest (ROI). Using the four number sliders below, choose the initial area of interest. the X,Y numbers define the top left of the rectangular area of interest, while the width and height define the rectangle dimensions. The rectangle will be drawn on the image to help guide you.
70
+ **NOTE: The ROI is always set on the first frame, so ensure you are on that image frame when setting the ROI.**
71
+
72
+ Once you are ready, click the "Start Object Tracking" button below the image.
73
+ ''')
74
+ # Save the uploaded video file to a temporary file
75
+ tfile = tempfile.NamedTemporaryFile(delete=False)
76
+ tfile.write(uploaded_file.read())
77
+ file_name, _ = os.path.splitext(uploaded_file.name)
78
+
79
+
80
+
81
+ # Read the first frame of the video from the temporary file
82
+ vcap = cv2.VideoCapture(tfile.name)
83
+ total_frames = int(vcap.get(cv2.CAP_PROP_FRAME_COUNT))
84
+
85
+ # Close and delete the temporary file
86
+ tfile.close()
87
+
88
+ instructions_container = st.empty()
89
+ left_column,right_column = st.columns(2)
90
+
91
+ # User input for frame number
92
+ frame_number = st.number_input(f'Enter a frame number between 1 and {total_frames}', min_value=1, max_value=total_frames, value=1)
93
+ if frame_number >1:
94
+ st.warning("WARNING: When setting the region of interest (ROI) please ensure that you are defining the region based on Frame #1.")
95
+
96
+ # Options for adjustments
97
+ st.sidebar.header("Image adjustments")
98
+ grayscale = st.sidebar.checkbox("Convert to Grayscale")
99
+ contrast = st.sidebar.slider("Contrast", 1.0, 3.0, 1.0)
100
+ blur = st.sidebar.slider("Blur", 0, 10, 0)
101
+ edges = st.sidebar.checkbox("Edge Detection")
102
+ # Options for edge detection adjustments
103
+ lower_threshold = 0
104
+ upper_threshold = 0
105
+ if edges:
106
+ st.sidebar.header("Edge Detection Parameters")
107
+ lower_threshold = st.sidebar.slider("Lower Threshold", 0, 255, 100)
108
+ upper_threshold = st.sidebar.slider("Upper Threshold", 0, 255, 200)
109
+
110
+ sharpen_amount = st.sidebar.slider("Sharpen Amount", 0.0, 2.0, 0.0)
111
+ subtract_background = st.sidebar.checkbox("Background Subtraction")
112
+
113
+ # Options for binarization adjustments
114
+ binarize = st.sidebar.checkbox("Binarize")
115
+ binarize_threshold=0
116
+ if binarize:
117
+ st.sidebar.header("Binarization Parameters")
118
+ binarize_threshold = st.sidebar.slider("Binarization Threshold", 0, 255, 128)
119
+
120
+ # Seek to the specified frame
121
+ vcap.set(cv2.CAP_PROP_POS_FRAMES, frame_number-1)
122
+ success, frame = vcap.read()
123
+
124
+ if success:
125
+ # Manual ROI entry
126
+ with instructions_container:
127
+ st.write("Enter the Region of interest (ROI) coordinates")
128
+
129
+ with left_column:
130
+ x = st.number_input('Enter X coordinate of top-left corner', min_value=0, value=0)
131
+ w = st.number_input('Enter width of the ROI', min_value=1, value=100)
132
+ with right_column:
133
+ y = st.number_input('Enter Y coordinate of top-left corner', min_value=0, value=0)
134
+ h = st.number_input('Enter height of the ROI', min_value=1, value=100)
135
+ # Apply adjustments to the frame
136
+ adjusted_frame = apply_adjustments(frame, grayscale, contrast, blur, edges, sharpen_amount,
137
+ subtract_background, lower_threshold, upper_threshold, binarize,
138
+ binarize_threshold,
139
+ )
140
+
141
+ # Draw the rectangle on the frame
142
+ cv2.rectangle(adjusted_frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
143
+ # Display the adjusted frame
144
+ st.image(Image.fromarray(adjusted_frame), caption=f'Adjusted Frame at {frame_number}', use_column_width=True)
145
+
146
+ else:
147
+ st.error(f"Could not read frame number {frame_number}.")
148
+ st.write('---')
149
+ # Release the video capture object
150
+ # vcap.release()
151
+ return vcap,file_name,total_frames,grayscale, contrast, blur, edges, sharpen_amount, subtract_background, lower_threshold, upper_threshold, binarize, binarize_threshold, x,y,w,h
152
+
153
+ ###############################################################################
154
+ ###############################################################################
155
+ ###############################################################################
156
+ def part_three(vcap,temp_dir,file_name, grayscale, contrast, blur, edges, sharpen_amount, subtract_background, lower_threshold, upper_threshold, binarize, binarize_threshold,x,y,w,h):
157
+ st.subheader('Part Three: Your object being tracked!')
158
+ st.write("...please be patient, it may take some time...")
159
+ vcap.set(cv2.CAP_PROP_POS_FRAMES, 0)
160
+ # Initialize the object tracker
161
+ tracker = cv2.TrackerCSRT_create()
162
+
163
+ #initialize positions
164
+ x_position = []
165
+ y_position = []
166
+ w_position = []
167
+ h_position = []
168
+
169
+
170
+
171
+ # Read the first frame
172
+ success, frame = vcap.read()
173
+ if success:
174
+ # Get video properties
175
+ frame_width = int(vcap.get(cv2.CAP_PROP_FRAME_WIDTH))
176
+ frame_height = int(vcap.get(cv2.CAP_PROP_FRAME_HEIGHT))
177
+ fps = vcap.get(cv2.CAP_PROP_FPS)
178
+
179
+ # Define the codec and create VideoWriter object
180
+ fourcc = cv2.VideoWriter_fourcc(*'XVID')
181
+ out = cv2.VideoWriter(f'{temp_dir}/{file_name}_ADJUSTED.avi', fourcc, fps, (frame_width, frame_height))
182
+
183
+ # Apply adjustments to the first frame
184
+ adjusted_frame = apply_adjustments(frame, grayscale, contrast, blur, edges, sharpen_amount, subtract_background, lower_threshold, upper_threshold, binarize, binarize_threshold)
185
+
186
+ # Define an initial bounding box
187
+ bbox = (x, y, w, h)
188
+
189
+ # Initialize tracker with first frame and bounding box
190
+ tracker.init(adjusted_frame, bbox)
191
+
192
+ tracking_image_box = st.empty()
193
+ tracking_image_info = st.empty()
194
+ # Loop over the frames of the video
195
+ frame_number = 0
196
+ while True:
197
+ # Read a new frame
198
+ success, frame = vcap.read()
199
+ if not success:
200
+ break
201
+ # Apply adjustments to the frame
202
+ adjusted_frame = apply_adjustments(frame, grayscale, contrast, blur, edges, sharpen_amount, subtract_background, lower_threshold, upper_threshold, binarize, binarize_threshold)
203
+ # Update tracker
204
+ success_tracker, box = tracker.update(adjusted_frame)
205
+ if success_tracker:
206
+
207
+ # Draw the tracking box
208
+ (x, y, w, h) = [int(v) for v in box]
209
+ cv2.rectangle(adjusted_frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
210
+ # Write the adjusted frame to the output video
211
+ out.write(adjusted_frame)
212
+ with tracking_image_info:
213
+ st.write(f'''
214
+ Frame number: {frame_number+1} (of {total_frames-1})
215
+ (x-position, y-position, width, height) = ''',x,y,w,h)
216
+ x_position.append(x)
217
+ y_position.append(y)
218
+ w_position.append(w)
219
+ h_position.append(h)
220
+ # Display the tracked frame
221
+ with tracking_image_box:
222
+ st.image(Image.fromarray(adjusted_frame), caption='Tracked Frame', use_column_width=True)
223
+ frame_number += 1
224
+
225
+ #Plot x and y over time
226
+ t = np.linspace(1,len(x_position),len(x_position)) - 1
227
+ df = pd.DataFrame({
228
+ 'Frame number' : t,
229
+ 'Horizontal pixel' : x_position,
230
+ 'Vertical pixel' : y_position,
231
+ 'Box width' : w_position,
232
+ 'Box height' : h_position
233
+ })
234
+ else:
235
+ df=pd.DataFrame()
236
+ # Release the video capture object
237
+ vcap.release()
238
+ out.release()
239
+ return df
240
+
241
+
242
+ ###############################################################################
243
+ ###############################################################################
244
+ ###############################################################################
245
+ def part_four(df,file_name):
246
+ st.write("---")
247
+ st.subheader('Part four: RESULTS!')
248
+ st.write('''
249
+ A plot of the horizontal and vertical position of the tracking rectagle (ROI) is displayed in the graph below.
250
+ You can zoom in and hover over specific parts of the graph as desired.
251
+ Note, the x-axis is frame number (not time) and the y-axis is pixel position. You will need to convert these to time and distance in your units of interest.
252
+ ''')
253
+ st.line_chart(
254
+ df, x="Frame number", y=["Horizontal pixel", "Vertical pixel"], color=["#FF0000", "#0000FF"] # Optional
255
+ )
256
+ st.write("Please use the two buttons below to download the pixel tracking results as a xlsx file, and a movie of the adjusted video as an avi file.")
257
+
258
+
259
+ col_a,col_b = st.columns(2)
260
+ # Function to convert DataFrame to Excel and return a BytesIO object
261
+ def to_excel(df):
262
+ output = BytesIO()
263
+ with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
264
+ df.to_excel(writer, index=False, sheet_name='Sheet1')
265
+ # No need to call writer.save() as it is handled by the context manager
266
+ processed_data = output.getvalue()
267
+ return processed_data
268
+
269
+ if len(df)>0:
270
+ # Download button
271
+ @st.experimental_fragment
272
+ def download_excel_results():
273
+ st.download_button(
274
+ label="Download Excel Results File",
275
+ data=to_excel(df),
276
+ file_name=f"{file_name}.xlsx",
277
+ mime="application/vnd.ms-excel"
278
+ )
279
+ with col_a:
280
+ download_excel_results()
281
+
282
+ with open(f'{temp_dir}/{file_name}_ADJUSTED.avi', 'rb') as file:
283
+ video_bytes = file.read()
284
+ @st.experimental_fragment
285
+ def download_video_results(video_bytes):
286
+ st.download_button(
287
+ label="Download Video",
288
+ data=video_bytes,
289
+ file_name=f'{file_name}_ADJUSTED.avi',
290
+ mime="video/avi"
291
+ )
292
+ # video_file.close() # Close the file
293
+ with col_b:
294
+ # Function to convert file to a download link
295
+ if temp_dir:
296
+ download_video_results(video_bytes)
297
+
298
+ ###############################################################################
299
+ ###############################################################################
300
+ ###############################################################################
301
+
302
+ with tempfile.TemporaryDirectory() as temp_dir:
303
+ # Streamlit app
304
+ st.title('Cell squashing tracker!')
305
+
306
+ st.write('---')
307
+ # File uploader
308
+ uploaded_file = part_one()
309
+ st.write('---')
310
+
311
+ # If a file is uploaded
312
+ if uploaded_file is not None:
313
+ #Image adjustment and ROI
314
+ vcap,file_name,total_frames,grayscale, contrast, blur, edges, sharpen_amount, subtract_background, lower_threshold, upper_threshold, binarize, binarize_threshold, x,y,w,h = part_two(uploaded_file)
315
+ # Button to start object tracking
316
+ if st.button('Start Object Tracking'):
317
+ #start tracking
318
+ df = part_three(vcap,temp_dir,file_name, grayscale, contrast, blur, edges, sharpen_amount, subtract_background, lower_threshold, upper_threshold, binarize, binarize_threshold,x,y,w,h)
319
+ #display/download results
320
+ part_four(df,file_name)
321
+ else:
322
+ st.info("Upload a video file to get started.")
323
+