How to show webcam capture in Plone site using OpenCV? - python

I am using Plone 4.3. I am trying to create a face recognition system on the Plone site. I need to show webcam captures using a template page. My sample code is below. However, when I run this code, I can't get the captured image in the template file.
sample.py:
class video(BrowserView):
video=ViewPageTemplateFile('video.pt')
def chow(self):
return self.video()
def show_video(self):
import cv2.cv as cv
cv.NamedWindow("camera", 1)
capture = cv.CaptureFromCAM(0)
while True:
img = cv.QueryFrame(capture)
return img
video.pt:
<div id="res">
<!--Here face is url name-->
<img id="draw" tal:attributes="src python:context.absolute_url() + '/face'">
<!--the above line refers to call a method of show_video()-->
</div>

This is a good starting point: http://plone.org/products/collective.takeaportrait (activate the optional OpenCV integration).
Keep in mind that there's a big difference between showing the camera output on the screen (that is simply HTML 5) and performing face recognition server side.

Related

Trying to put PyTesseract OCR on web

I am using Pytesseract OCR for text detection and I am using a jupyter notebook to run it right now so the output is just popping up as another window. My output for the program is an image. Basically, I am trying to allow the user to input their own image and then the program will output another image on the website.
I am trying to do this but I am getting an error when I try loading the website. Here is my code:
import cv2
import matplotlib.pyplot as plt
from flask import Flask, request, Response
pytesseract.pytesseract.tesseract_cmd = 'C:\\Camera_Flask_App-main\\Tesseract\\tesseract.exe'
def pytess(img):
hImg,wImg,_ = img.shape
boxes = pytesseract.image_to_boxes(img)
for b in boxes.splitlines():
print(b[0])
b = b.split(' ')
x,y,w,h= int(b[1]),int(b[2]),int(b[3]),int(b[4])
cv2.rectangle(img,(x,hImg-y),(w,hImg-h),(0,0,255), 2)
cv2.putText(img,b[0],(x,hImg-y+25), cv2.FONT_HERSHEY_COMPLEX,1,(50,50,255),2)
##Detecting Words
hImg,wImg,_ = img.shape
boxes = pytesseract.image_to_data(img)
for x,b in enumerate(boxes.splitlines()):
if x!=0:
b = b.split()
if len(b)==12:
x,y,w,h= int(b[6]),int(b[7]),int(b[8]),int(b[9])
cv2.rectangle(img,(x,y),(w+x,h+y),(0,0,255), 2)
cv2.putText(img,b[11],(x,y), cv2.FONT_HERSHEY_COMPLEX,1,(50,50,255),2)
return img
# Initialize Flask application
app = Flask(__name__)
# POST request for running OCR
#app.route('/', methods=['GET', 'POST'])
def run_ocr():
image = request.files["image"]
#Read the image via file.stream, returns PIL image (may need to convert)
img = Image.open(image.stream)
# run ocr on image (you will need to update your function to return img)
processed_img = pytess(img)
# prepare image for response
_, img_encoded = cv2.imencode('.png', processed_img)
response = img_encoded.tostring()
# return png img with OCR shown
return Response(response=response, status=200, mimetype='image/png')
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=image>
<input type=submit value=Upload>
</form>
'''
if __name__ == '__main__':
app.run()
This is the error I am getting when I launch the site (not even put any picture):
error image
I got some feedback from another person and he said "You need to make sure that when you send the request you have the format as “multipart/form-data” with the “image” field set as the file" and when I asked him to help me fix the code he said, "I can’t change it here. It isn’t part of the code. Once you deploy the Flask server, it would be in the actual request to the server that you need to distinguish the data format". I am not really sure how to do this.
Can anyone help? Thanks!

how to capture and import RAW or .DNG image directly from an iPhone 13 on a mobile device?

I am attempting to capture or import RAW images directly from a small python script to import for further analysis. I am attempting to create a simple mobile code to run on pythnissta 3 or similar platform to stream line my analysis. I have tried a few things to import the last taken image form the photo library but my attempts were unfruitful:
import photos
all_assets = photos.get_assests()
last_asset = all_assests[-1]
img = last_assest.image()
img. show
To capture images directly:
import photos
import console
console.clear()
nom_album = contacts
photos.create_album(nom_album)
img = photos.capture_image()
Here's a link to an example image.This is a .DNG image taken under the Pro RAW settings from an iPhone 13 pro.

Not able to send webcam video to template(.html) file using StreamingHttpResponse in Django 2.2

I recently started django and I wanted to see the video from the laptop camera to Django 2.2 based web app. I was successful in viewing the cam video by directly sending response to web using function display_livefeed. Following is my code of views.py of app 'camerafeed'
class mycamera(object):
def __init__(self):
self.frames = cv2.VideoCapture(0)
def __del__(self):
self.frames.release()
def get_jpg_frame(self):
is_captured, frame = self.frames.read()
retval, jframe = cv2.imencode('.jpg', frame)
return jframe.tobytes()
def livefeed():
camera_object = mycamera()
while True:
jframe_bytes = camera_object.get_jpg_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + jframe_bytes + b'\r\n\r\n')
#condition(etag_func=None)
def display_livefeed(self):
return StreamingHttpResponse(
livefeed(),
content_type='multipart/x-mixed-replace; boundary=frame'
)
I used path('monitor/', display_livefeed, name='monitor'), to see the video streaming on http://127.0.0.1:8000/monitor/ and it works perfectly >>Image from the streaming video<<
Now I wanted to display on the html template just line it is done here:
https://www.pyimagesearch.com/2019/09/02/opencv-stream-video-to-web-browser-html-page/
but this was done by using Flask. But I wanted to do the same using Django and got stuck. Here is the html file from the above link.
<html>
<head>
<title>Pi Video Surveillance</title>
</head>
<body>
<h1>Pi Video Surveillance</h1>
<img src="{{ url_for('video_feed') }}">
</body>
I tried to do like this using by making this function:
def video_feed(request):
return StreamingHttpResponse(
livefeed(), # Calling livefeed() function
content_type='multipart/x-mixed-replace; boundary=frame'
)
But it able to see the video on html page using path('', homePageView.as_view(), name='home'), and placing code below in views.py
class homePageView(TemplateView):
template_name = 'home.html'
I seen and tried following:
Django StreamingHttpResponse into a Template
Opencv Live Stream from camera in Django Webpage
But may be due to the fact that i am new to all these thing including web development, I might not able to get it done. Kindly help explaining me how to do this.
I am using python 3.7 and django 2.2
I solved it, disable the monitor path from the urlpatterns. I think that the trouble is that two sources are trying to use the camera. Just comment the
path('monitor', views.display_livefeed, name="monitor")
and it works.

Render image from request in bottle

My intention is to upload an image and do some image processing. For now, I intend to render the uploaded image.
I used the code here to build my front end and I wrote the backend in python using bottle, which is as follows:
#route('/test', method='POST')
def serve_image():
# import pdb; pdb.set_trace()
image = Image.open(request.body)
image.show()
I get an errors as follows
OSError: cannot identify image file <_io.BytesIO object at
0x0000017386B53A40>
What am I missing?
EDIT:
When I print the whole request, this is what I get
< http://localhost:8080/test>
That tutorial is not very comprehensive, but the full documentation is more useful:
The image data is uploaded as part of a standard multipart form post, and included as a form element named webcam.
So rather than trying to pass the whole request body to Pillow, you need to pass just that element, using the request.files multidict, and accessing its file attribute to get the buffer:
image = Image.open(request.files['webcam'].file)

Displaying image in template with Flask?

So I am hosting some user-uploaded images on my site. I want to have an html page that displays the image inline, and some data about it on the side, etc. I've set up my app with two handlers, one that displays the image on the page that uses a url_for to get the url for the raw image(e.g. i.mysite.com/image.jpg). It displays on the page fine, but takes forever to load. When I remove this function and just generate a URL for the image alone without the page, it loads instantly. Is this just a flask thing that will be remedied in a production environment with a real webserver, or is there another way I should be doing this? The images are not in the /static folder, they are in their own folder. I get the url for the raw image link in the handler for the function that displays the page with the image on it, and pass that as a path to the template.
#app.route('/<filename>', subdomain='i')
def uploaded_image(filename):
return send_from_directory(app.config['IMAGE_FOLDER'], filename)
#app.route('/<tag>/', subdomain='i', methods=['GET'])
def display_image(tag):
file = Storedfile.query.filter_by(routing_id=tag).first()
filename = file.name
return render_template("image-page.html", source=url_for('uploaded_image', filename=filename))
Like I said it displays the image fine, but takes forever to load, and when I inspect the image on the page with FF's dev tools, instead of seeing an actual URL, I see something like
<img src="/pyhE4eJ.jpg"></img>
For the other links, I get actual URLS that are made from functions, like
Shouldn't the source for the image be looking like this too?

Categories

Resources