Skip to content

Commit

Permalink
with opencv webcam and fonts
Browse files Browse the repository at this point in the history
  • Loading branch information
Hasham268 committed Jul 4, 2024
1 parent bf1b948 commit 86cb28d
Show file tree
Hide file tree
Showing 12 changed files with 167 additions and 46 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/flask/*.h5
/flask/*.pt
/flask/venv

# Logs
logs
Expand Down
Binary file added assets/Gilroy-ExtraBold.otf
Binary file not shown.
Binary file added assets/Gilroy-Light.otf
Binary file not shown.
Binary file modified flask/__pycache__/torch_inference.cpython-38.pyc
Binary file not shown.
64 changes: 63 additions & 1 deletion flask/app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import base64
import cv2
import numpy as np
from flask import Flask, request, jsonify
from flask import Flask, request, jsonify, Response
from flask_cors import CORS
from PIL import Image
import io
Expand All @@ -13,10 +13,15 @@
from torch_inference import infer
from keras.models import load_model
from scipy.ndimage import rotate as scipy_rotate
# from yoloseg import YOLOSeg

app = Flask(__name__)
CORS(app, origins=['*'])

# Initialize YOLOv5 Instance Segmentator
# model_path = "models/yolov8m-seg.onnx"
# yoloseg = YOLOSeg(model_path, conf_thres=0.3, iou_thres=0.3)

model2 = YOLO('./yolov8n.pt')

def rotation(image):
Expand Down Expand Up @@ -210,6 +215,63 @@ def detect_objects():
except Exception as e:
return jsonify({"error": str(e)}), 500

def webcam_yolo():
camera = cv2.VideoCapture(0)
model = YOLO('yolov8n.pt')
# 0 represents the default webcam
while True:
ret, frame = camera.read()
if not ret:
break
results = model(frame)
# Process the frame with YOLO
annotated_frame = results[0].plot()

cv2.imshow("Detected Objects", annotated_frame)

if cv2.waitKey(1) & 0xFF == ord('q'):
break

# # Encode the annotated frame as JPEG
# _, buffer = cv2.imencode('.jpg', annotated_frame)

# # Send the frame as a multipart response
# yield (b'--frame\r\n'
# b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')

camera.release()
cv2.destroyAllWindows()

# @app.route('/yolo_feed')
# def yolo_feed():
# return Response(webcam_yolo(), mimetype='multipart/x-mixed-replace; boundary=frame')


# def generate_frames():
# cap = cv2.VideoCapture(0)

# while cap.isOpened():
# ret, frame = cap.read()
# if not ret:
# break

# boxes, scores, class_ids, masks = yoloseg(frame)
# combined_img = yoloseg.draw_masks(frame)

# # Display the image in a new window
# cv2.imshow("Detected Objects", combined_img)

# if cv2.waitKey(1) & 0xFF == ord('q'):
# break

# cap.release()
# cv2.destroyAllWindows()

@app.route('/video_feed')
def video_feed():
# Call the function to start displaying frames
webcam_yolo()
return "Video feed started."

if __name__ == '__main__':
app.run(debug=True)
Binary file added flask/req2.txt
Binary file not shown.
56 changes: 28 additions & 28 deletions src/nodes/WebcamNode.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,33 @@ import PropTypes from 'prop-types';
import { Handle, Position } from 'reactflow';

function WebcamInputNode({ data }) {
const videoRef = useRef(null);

useEffect(() => {
let stream;

const initializeWebcam = async () => {
try {
stream = await navigator.mediaDevices.getUserMedia({
video: true,
});
if (videoRef.current) {
videoRef.current.srcObject = stream;
data.onVideoUpload(stream);
}
} catch (error) {
console.error('Error accessing webcam:', error);
}
};

initializeWebcam();

return () => {
if (stream) {
stream.getTracks().forEach((track) => track.stop());
}
};
}, [data]);
// const videoRef = useRef(null);

// useEffect(() => {
// let stream;

// const initializeWebcam = async () => {
// try {
// stream = await navigator.mediaDevices.getUserMedia({
// video: true,
// });
// if (videoRef.current) {
// videoRef.current.srcObject = stream;
// data.onVideoUpload(stream);
// }
// } catch (error) {
// console.error('Error accessing webcam:', error);
// }
// };

// initializeWebcam();

// return () => {
// if (stream) {
// stream.getTracks().forEach((track) => track.stop());
// }
// };
// }, [data]);

return (
<div className=" p-6 rounded-3xl border border-1 border-[#FFF]" style={{
Expand All @@ -39,7 +39,7 @@ function WebcamInputNode({ data }) {
Webcam
</h3>
<div style={{width: '220px'}}>
<video ref={videoRef} autoPlay playsInline />
{/* <video ref={videoRef} autoPlay playsInline /> */}
</div>
<Handle type="source" position={Position.Right} />
</div>
Expand Down
6 changes: 6 additions & 0 deletions src/renderer/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ body::-webkit-scrollbar {

}

@font-face {
font-family: 'Gilroy';
src: url('../../assets/Gilroy-Light.otf') format('truetype');
font-weight: normal;
font-style: normal;
}


.right{
Expand Down
29 changes: 16 additions & 13 deletions src/renderer/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'reactflow/dist/style.css';
import Theme from '../utils/theme';
import Landing from './Landing';
import { ContextProvider } from '../utils/MyContext';
import Sequences from './Sequences';

function App() {
const [parentProjectType, setParentProjectType] = useState(null);
Expand All @@ -17,19 +18,21 @@ function App() {

return (
<ContextProvider>
<Router>
<Theme />
<Routes>
<Route
path="/"
element={<Landing onProjectTypeChange={handleProjectTypeChange} />}
/>
<Route
path="/flow"
element={<Flow projectType={parentProjectType} />}
/>
</Routes>
</Router>
<Router>
<Theme />
<Routes>
<Route
path="/"
element={<Landing onProjectTypeChange={handleProjectTypeChange} />}
/>
<Route
path="/flow"
element={<Flow projectType={parentProjectType} />}
/>

{/* <Route path="/seq" element={<Sequences />} /> */}
</Routes>
</Router>
</ContextProvider>
);
}
Expand Down
36 changes: 32 additions & 4 deletions src/renderer/Flow.js
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,24 @@ function Flow({ projectType }) {
}
}, [shouldTriggerRequest, inputImage, triggerBackendRequest]);

function openVideoFeedWindow() {
const videoFeedWindow = window.open(
'http://localhost:5000/yolo_feed',
'Yolo Feed',
'width=640,height=480',
);
if (videoFeedWindow) {
videoFeedWindow.onbeforeunload = () => {
console.log('Video feed window closed');

Check warning on line 318 in src/renderer/Flow.js

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest)

Unexpected console statement
// Handle cleanup or any necessary actions when the window is closed
};
} else {
alert(
'Failed to open video feed window. Please check popup blocker settings.',
);
}
}

const onConnect = useCallback(
(params) => {
const edge = {
Expand Down Expand Up @@ -493,7 +511,19 @@ function Flow({ projectType }) {
}

if (sourceNode.data.code === 'Vi' && targetNode.data.code === 'Od') {
startFrameCapture(videoStream);
// startFrameCapture(videoStream);
axios
.get('http://localhost:5000/video_feed')
.then((response) => {
// Handle success, if needed
console.log('Video feed started:', response.data);
})
.catch((error) => {
// Handle error, if needed
console.error('Error starting video feed:', error);
});

// openVideoFeedWindow();
}

// const newEdges = [...prevEdges, newEdge];
Expand Down Expand Up @@ -545,8 +575,6 @@ function Flow({ projectType }) {

axios
.post('http://localhost:5000/detectVideo', formData, {


headers: {
'Content-Type': 'multipart/form-data',
},
Expand Down Expand Up @@ -612,7 +640,7 @@ function Flow({ projectType }) {
frameCaptureStop();
setFlag(false);
}
if (targetNode.data.code === 'Od'){
if (targetNode.data.code === 'Od') {
frameCaptureStop();
setFlag(false);
}
Expand Down
12 changes: 12 additions & 0 deletions src/renderer/Landing.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@ export default function Landing({ onProjectTypeChange }) {
>
Use PreMade Nodes
</Link>

{/* <Link
to="/seq"
className=" text-white py-2 px-5 text-lg"
style={{
borderRadius: '20px',
background: 'linear-gradient(90deg, #876EE6 0%, #3E5FAA 100%)',
}}
>
Make Sequences
</Link> */}
</div>
</div>
</div>
Expand Down
9 changes: 9 additions & 0 deletions src/renderer/Sequences.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React from 'react'

const Sequences = () => {
return (
<div>Sequences</div>
)
}

export default Sequences

0 comments on commit 86cb28d

Please sign in to comment.