score:1
gen()
runs loop which all time uses the same frame()
.
you have to get frame
inside this loop.
def gen():
while true:
frame = color_detection.color_detection(0)
if frame:
yield b'--frame\r\ncontent-type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n'
#else:
# print('no frame')
but color_detection
should run without loop
.
and you should create videocapture(1)
only once.
and you should return frame
even if you didn't detect any face.
path = os.path.join(cv2.data.haarcascades, 'haarcascade_frontalface_default.xml')
face_cascade = cv2.cascadeclassifier(path)
video = cv2.videocapture(1)
def color_detection(season):
# ret tells if the camera works properly. frame is an actual frame from the video feed
ret, frame = video.read()
# make sure port is working and read the image
if frame is not none and video.isopened():
gray = cv2.cvtcolor(frame, cv2.color_bgr2gray)
'''
detect the faces within the subregions of the image in scales
scalefactor indicates how much the image size is reduced at each image scale.
minneighbors: higher value results in higher quality of the detected face.
'''
faces = face_cascade.detectmultiscale(gray, scalefactor=1.1, minneighbors=6)
# draw circle around each face
for (x, y, w, h) in faces:
# use the stcoordinates to find the center of the face and from that point draw a rectangle of radius w/2 or h/2.
center_coordinates = x + w // 2, y + h // 2
radius = w // 2 # or can be h / 2 or can be anything based on your requirements
# background color(black)
mask = np.zeros(frame.shape[:2], dtype="uint8")
# draw the desired region to crop out in white
cv2.circle(mask, center_coordinates, radius, (255, 255, 255), -1)
masked = cv2.bitwise_and(frame, frame, mask=mask)
if season == 0: # spring
# replace all (0,0,0)channel with coral pink
masked[np.where((masked == [0, 0, 0]).all(axis=2))] = [121, 131, 248]
elif season == 1: # summer
#replace all (0,0,0)channel with rose red
masked[np.where((masked==[0,0,0]).all(axis=2))] = [86,30,194]
elif season == 2: # fall
#replace all (0,0,0)channel with red brown /cinnamon
masked[np.where((masked==[0,0,0]).all(axis=2))] = [30,105,210]
else: # winter
#replace all (0,0,0)channel with burgundy red
masked[np.where((masked==[0,0,0]).all(axis=2))] = [31,2,141]
ret, jpeg = cv2.imencode('.jpg', masked)
else: # it is `for/else` construction, not `if/else`
ret, jpeg = cv2.imencode('.jpg', frame)
return jpeg.tobytes()
#return none
btw:
i see other problem. when it detects many faces then it creates new mask for every face and assigns every mask to original image - so every mask skip previous mask - so it should show only last face, and hide other faces. you should first create one mask with all circles and next use it on image.
edit:
i don't know what web framework you use so i used flask
to create minimal working example.
import os
from flask import flask, response
import cv2
import numpy as np
app = flask(__name__)
print('\n'.join(sorted(os.listdir(cv2.data.haarcascades))))
path = os.path.join(cv2.data.haarcascades, 'haarcascade_frontalface_default.xml')
face_cascade = cv2.cascadeclassifier(path)
#video = cv2.videocapture(0) # my webcam
video = cv2.videocapture(0) # your webcam
def color_detection(season):
ret, frame = video.read()
if frame is not none and video.isopened():
gray = cv2.cvtcolor(frame, cv2.color_bgr2gray)
faces = face_cascade.detectmultiscale(gray, scalefactor=1.1, minneighbors=6)
# test two circles on image 640x480
#faces = [[100, 100, 250, 250], [640-100-250, 480-100-250, 250, 250]]
if len(faces) > 0: # it can be `if faces:` because `faces` is `numpy array` which need different method to check if not empty
# background color(black)
mask = np.zeros(frame.shape[:2], dtype="uint8")
# draw all circles on mask
for (x, y, w, h) in faces:
#print(x, y, w, h)
# use the coordinates to find the center of the face and from that point draw a rectangle of radius w/2 or h/2.
center_coordinates = x + w // 2, y + h // 2
radius = max(w, h) // 2 # or can be h / 2 or can be anything based on your requirements
# draw the desired region to crop out in white
cv2.circle(mask, center_coordinates, radius, (255, 255, 255), -1)
# use mask with all circles
masked = cv2.bitwise_and(frame, frame, mask=mask)
if season == 0: # spring - coral pink
color = [121, 131, 248]
elif season == 1: # summer - rose red
color = [86,30,194]
elif season == 2: # fall - red brown /cinnamon
color = [30,105,210]
else: # winter - burgundy red
color = [31,2,141]
masked[np.where((masked == [0,0,0]).all(axis=2))] = color
else: # no faces
masked = frame
ret, jpeg = cv2.imencode('.jpg', masked)
return jpeg.tobytes()
def gen():
while true:
frame = color_detection(0)
if frame:
yield (b'--frame\r\ncontent-type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
#else:
# print('no frame')
@app.route('/')
def index():
return '<image src="/seasoncolor">'
@app.route('/seasoncolor')
def seasoncolor():
return response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
#app.debug = true
app.run()
btw:
to make sure: videocapture
can work only with local camera where you run web server. it can't work with remote camera on user computer. only user's browser has access to its camera. to work with remote camera on user computer you would have to use javascript
to access camera in user browser and send frames to server - like in my examples in my github python-examples
: web camera in browser - canvas - take image and upload to server
Source: stackoverflow.com
Related Query
- Apply mask to Webcam streaming in opencv
- How to apply a half circle mask to an image and add a button inside an image in ReactJS using ant design?
- How to apply global styles with CSS modules in a react app?
- How to apply custom animation effect @keyframes in MUI?
- How do I apply vendor prefixes to inline styles in reactjs?
- How to apply CSS and Styling to a React component
- How to apply different color in AppBar Title MUI?
- How to conditionally apply CSS classes in React JS
- How Can I Mask My Material-UI TextField?
- Invalid hook call. Hooks can only be called inside of the body of a function component when apply style to class base component with material-ui
- Apply style "cursor: pointer" to all React components with onClick function
- How to apply lazy loading in flatlist in react native
- How to apply custom theme in material ui
- How to apply a pattern to a TextField to only allow specific characters
- Material-UI - Apply max-height to Select children
- How to apply antd dark theme for a React App?
- React - How to apply CSS styles to iframe content
- How to apply fontSize to CardHeader title in MUI?
- ReactJS apply multiple inline styles
- How to apply useEffect based on form submission in React?
- Is there a way to apply a fade in/out transition with React suspense for the fallback component?
- React JS: Apply Material-UI CssBaseline
- React CSS - how to apply CSS to specific pages only
- How to stream webcam feed on web page using react js component?
- Mask Textfield component in Material-UI
- Apply styled component style to a third party components
- How do I get typography theme defaults to apply to regular tags with Material-UI?
- How do I apply a Font Theme in React Material-UI?
- How would I apply Material-UI managed styles to non-material-ui, non-react elements?
- react-icons apply a linear gradient
More Query from same tag
- How to call a function which has a same name with a parameter
- flex box with images in a row
- Reuse everything from a React component except its render method
- Form submission with redux-saga
- Web Audio Related React Problems
- history.push() using react-router-dom works in some components but not others
- Trying to dynamically add new rows in React
- React redux dispatch not available
- how to hide and show componet in react js using a single button
- React error when using map
- apexcharts - candlestick chart with extra line - how to change line color?
- Reactjs post multiple values including a file to ASP.Net Core controller action
- How can I upload Images with Preview in React
- i am using for loop in object in javascript, but one condition is creating issue
- Apply onChange effect on a select option
- useMemo behaves different for inline component vs. normal component
- Social media share not picking up meta tags in react-app via react-helmet or react-meta-tags
- Avoid to rerender on every change event in React
- React router can't pass params
- Using .env.local file for API Credentials to connect to my Airtable DB
- Using In App Browser cordova plugin with typescript
- ReactJS with Webpack: Uncaught ReferenceError: require is not defined
- Rendering invalid credentials message in React on Rails App
- Can I stop a click from triggering website's usual actions?
- Can you include a Svelte Component in a ReactJS project?
- How to find declaration for my typescript/react module?
- Undefined is not an object (evaluating 'users.map') REACT NATIVE
- HTML Audio component controls not showing download in Safari
- Can state be named differently (with another name like 'globalState') in ReactJS?
- firebaseApp is not defined in firebase file