File size: 11,067 Bytes
3411a6b c2bc888 3fe8680 3411a6b 3fe8680 9541d8f 3fe8680 e0fe2fb 3fe8680 5f711c5 3fe8680 7eaf29d 5f711c5 7eaf29d 3fe8680 53b1eaf 3fe8680 960f68e 3fe8680 e19b5ff |
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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 |
import streamlit as st
import pandas as pd
st.subheader(":red[**Video Capture -**]")
st.write("Video capture is the process of accessing and reading video streams (e.g., from a camera or a video file) in a program. Here's a step-by-step explanation of how video capture works, primarily using OpenCV, a popular library for computer vision tasks in Python.")
st.write("**Import Necessary Libraries**")
st.write("To handle video capture, you need a library like OpenCV. Begin by importing it:")
code="""
import numpy as np
import cv2
"""
st.code(code,language="python")
st.write(":blue[**1. Initialize the Video Capture**]")
code="""
vid = cv2.VideoCapture(0) # Use path for a video file or 0 for the default webcam
"""
st.code(code,language="python")
st.write("""
- **cv2.VideoCapture(0):**
- 0 refers to the default webcam of the system.
- You can replace 0 with 1, 2, etc., for other cameras.
- If you're capturing from a file, provide the file path as a string (e.g., 'video.mp4').
""")
st.write(":blue[**2. Start an Infinite Loop for Frame Capture**]")
code="""
while True: # This loop keeps running, continuously reading frames from the video source (webcam).
"""
st.code(code,language="python")
st.write(":blue[**3. Read Frames**]")
code="""
succ, img = vid.read()
"""
st.code(code,language="python")
st.write("""
- vid.read
- Returns two values:
1.succ: A boolean that is True if the frame is read successfully, False otherwise.
2.img: The captured frame, represented as a NumPy array.
""")
st.write(":blue[**4. Handle Errors**]")
code="""
if succ == False:
print("camera not working")
break
"""
st.code(code,language="python")
st.write("""
- If succ is False, it indicates the camera isn't working or the video stream cannot be accessed.
- The loop exits if the camera isn't functioning.
""")
st.write(":blue[**5. Display the Frame**]")
code="""
cv2.imshow("live stream", img)
"""
st.code(code,language="python")
st.write("""
- cv2.imshow():
- Displays the captured frame (img) in a window titled "live stream."
- The frame is updated in real time.
""")
st.write(":blue[**6. Exit on Key Press**]")
code="""
if cv2.waitKey(1) & 255 == ord("w"):
break
"""
st.code(code,language="python")
st.write("""
- **cv2.waitKey(1):**
- Waits for 1 millisecond for a key press.
- The & 255 ensures compatibility with certain systems where cv2.waitKey can return larger values.
- **ord("w"):**
- Detects if the w key is pressed.
- If pressed, the loop breaks, stopping the video stream.
""")
st.write(":blue[**7. Clean Up Resources**]")
code="""
cv2.destroyAllWindows() #Closes all OpenCV windows that were opened using cv2.imshow().
"""
st.code(code,language="python")
st.write(":blue[**Complete Code with Comments**]")
st.write(":blue[**1.code**]")
code="""
import cv2
# Initialize video capture (0 for default webcam)
vid = cv2.VideoCapture(0)
while True:
# Capture a frame
succ, img = vid.read()
# Check if the frame was successfully read
if not succ:
print("Camera not working")
break
# Display the frame in a window
cv2.imshow("Live Stream", img)
# Exit the loop if the 'w' key is pressed
if cv2.waitKey(1) & 255 == ord("w"):
break
# Release the camera and close all OpenCV windows
vid.release()
cv2.destroyAllWindows()
"""
st.code(code,language="python")
st.write(":blue[**Enhancements**]")
st.write("**1.Add Frame Processing: Apply transformations like grayscale, edge detection, or resizing before displaying.**")
code="""
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("Grayscale Live Stream", gray_img)
"""
st.code(code,language="python")
st.write("**2.Save Frames: Capture and save an image when a specific key (e.g., s) is pressed.**")
code="""
if cv2.waitKey(1) & 255 == ord("s"):
cv2.imwrite("captured_image.jpg", img)
"""
st.code(code,language="python")
st.write("**3.Handle Multiple Cameras: Use different indices for cv2.VideoCapture() to access other webcams if available.**")
st.write("**4.Real-Time FPS Display: Measure and display the frames per second (FPS) on the live stream.**")
st.write(":blue[**2.code**]")
code="""
import cv2
import numpy as np
# Initialize the video capture (0 for default webcam)
vid = cv2.VideoCapture(0)
while True:
# Capture frame
succ, img = vid.read()
if not succ:
print("Camera not working")
break
# Split the channels
b, g, r = cv2.split(img)
# Create a black canvas for channel visualization
z = np.zeros(b.shape, dtype=np.uint8)
# Display the original and individual color channels
cv2.imshow("live stream1", img) # Original video frame
cv2.imshow("live stream2", cv2.merge([b, z, z])) # Blue channel
cv2.imshow("live stream3", cv2.merge([z, g, z])) # Green channel
cv2.imshow("live stream4", cv2.merge([z, z, r])) # Red channel
# Exit when 'w' is pressed
if cv2.waitKey(1) & 255 == ord("w"):
break
# Release resources and close windows
vid.release()
cv2.destroyAllWindows()
"""
st.code(code,language="python")
st.write(":blue[**Code Explanation**]")
st.write("**1. Video Capture Initialization**")
code="""
vid = cv2.VideoCapture(0) # Access the default webcam (ID = 0)
"""
st.code(code,language="python")
st.write("""
- cv2.VideoCapture(0) initializes the video capture object using the system's default webcam.
- Replace 0 with a file path (e.g., 'video.mp4') to process a saved video.
""")
st.write("**2. Read Frames in a Loop**")
code="""
while True:
succ, img = vid.read()
if succ == False:
print("camera not working")
break
"""
st.code(code,language="python")
st.write("""
- The loop runs continuously, capturing video frames in real-time.
- succ: A boolean indicating whether a frame was captured successfully.
- img: The captured frame as a NumPy array.
If the camera isn't working or a frame cannot be captured, the loop exits.
""")
st.write("**3. Split Channels**")
code="""
b, g, r = cv2.split(img)
"""
st.code(code,language="python")
st.write("""
- cv2.split(img) decomposes the frame into its three color channels:
- b: Blue channel.
- g: Green channel.
- r: Red channel.
""")
st.write("**4. Create a Black Canvas for Channel Visualization**")
code="""
z = np.zeros(b.shape, dtype=np.uint8)
"""
st.code(code,language="python")
st.write("""
- np.zeros(b.shape, dtype=np.uint8) creates a black canvas of the same size as the frame's blue channel.
- This black canvas is used to replace other color channels when displaying a single channel.
""")
st.write("**5. Display Original and Channel-Specific Streams**")
code="""
cv2.imshow("live stream1", img) # Original video frame
cv2.imshow("live stream2", cv2.merge([b, z, z])) # Blue channel
cv2.imshow("live stream3", cv2.merge([z, g, z])) # Green channel
cv2.imshow("live stream4", cv2.merge([z, z, r])) # Red channel
"""
st.code(code,language="python")
st.write("""
1.cv2.imshow() displays the frames in separate windows:
- live stream1: The original frame.
- live stream2: The blue channel, visualized by merging it with two black channels.
- live stream3: The green channel, visualized similarly.
- live stream4: The red channel.
2.cv2.merge([channel1, channel2, channel3]) combines the individual channels to create a 3-channel image.
""")
st.write("**6. Exit on Key Press**")
code="""
if cv2.waitKey(1) & 255 == ord("w"):
break
"""
st.code(code,language="python")
st.write("""
- Waits for 1 millisecond to check if the w key is pressed.
- If w is detected, the loop breaks, stopping the video feed.
""")
st.write("**7. Clean Up Resources**")
code="""
import cv2
import os
# Create a directory to save images
os.makedirs("/home/user/han_sign", exist_ok=True)
# Initialize video capture
vid = cv2.VideoCapture(0)
# Initialize counter for image filenames
c = 0
try:
while True:
# Capture a frame
suc, img = vid.read()
if not suc:
print("Camera not working")
break
# Display the live stream
cv2.putText(img, "Press 's' to save, 'c' to exit", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imshow("Live Stream", img)
# Save the image when 's' key is pressed
if cv2.waitKey(1) & 255 == ord("s"):
cv2.imwrite(f"/home/user/han_sign/{c}.jpg", img)
print(f"Image {c} has been captured")
c += 1
# Exit when 'c' key is pressed
if cv2.waitKey(1) & 255 == ord("c"):
break
finally:
# Release resources and close windows
vid.release()
cv2.destroyAllWindows()
print(f"Total images captured: {c}")
"""
st.code(code,language="python")
st.write("**Code Explanation**")
st.write(":blue[**1. Create a Directory**]")
code="""
import os
os.makedirs("/home/user/han_sign)
"""
st.code(code,language="python")
st.write("""
- os.makedirs(path):
- Creates a directory at the specified path.
- In this case, a folder named han_sign is created in the Downloads directory.
""")
st.write(":blue[**2. Initialize Video Capture**]")
code="""
vid = cv2.VideoCapture(0)
"""
st.code(code,language="python")
st.write("""
- Initializes video capture using the default webcam (index 0).
- Replace 0 with a file path to use a video file instead.
""")
st.write(":blue[**3. Initialize Counter**]")
code="""
c = 0 #This counter is used to assign unique filenames to the captured images (e.g., 0.jpg, 1.jpg, ...).
"""
st.code(code,language="python")
st.write(":blue[**4. Start an Infinite Loop for Video Capture**]")
code="""
while True:
suc, img = vid.read()
if suc == False:
print("camera not working")
break
"""
st.code(code,language="python")
st.write("""
- Captures frames from the video stream in real time.
- suc is True if the frame is successfully captured.
- If suc is False, the loop exits, indicating a problem with the camera.
""")
st.write(":blue[**5. Save Images on Key Press**]")
code="""
if cv2.waitKey(1) & 255 == ord("s"):
cv2.imwrite("/home/user/han_sign"/{}.jpg".format(c), img)
print("image have been captured")
c += 1
"""
st.code(code,language="python")
st.write("""
- cv2.waitKey(1) & 255 == ord("s"):
- Detects if the s key is pressed.
- cv2.imwrite(path, img):
- Saves the current frame (img) as a .jpg file in the specified folder.
- The filename is determined by the counter c.
-c += 1:
Increments the counter to ensure the next image has a unique filename.
""")
st.write(":blue[**6. Exit on Key Press**]")
code="""
if cv2.waitKey(1) & 255 == ord("c"): #Detects if the c key is pressed, which exits the loop and stops the program.
break
"""
st.code(code,language="python")
st.write(":blue[**7. Release Resources**]")
code="""
cv2.destroyAllWindows() #Closes all OpenCV windows and releases resources.
"""
st.code(code,language="python")
|