File size: 1,481 Bytes
ff5fd92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import cv2
import numpy as np
from PIL import Image

def main():
    st.title("Webcam Grayscale Filter")
    st.write("This app applies a grayscale filter to your webcam feed.")
    
    # Add a placeholder for the webcam feed
    video_placeholder = st.empty()
    
    # Add a stop button
    stop_button = st.button("Stop")
    
    # Start the webcam
    cap = cv2.VideoCapture(0)
    
    # Check if the webcam is opened correctly
    if not cap.isOpened():
        st.error("Cannot open webcam. Please check your camera connection.")
        return
    
    while cap.isOpened() and not stop_button:
        # Read a frame from the webcam
        ret, frame = cap.read()
        
        if not ret:
            st.error("Failed to capture image from webcam.")
            break
        
        # Convert the frame to grayscale
        gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        
        # Convert grayscale frame to RGB for Streamlit display
        # (Streamlit expects RGB images)
        gray_rgb = cv2.cvtColor(gray_frame, cv2.COLOR_GRAY2RGB)
        
        # Display the frame in the Streamlit app
        video_placeholder.image(gray_rgb, channels="RGB", use_column_width=True)
        
        # Add a small delay
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    # Release resources
    cap.release()
    cv2.destroyAllWindows()
    st.write("Webcam stopped")

if __name__ == "__main__":
    main()