Use cv.CaptureFromCAM in Django - python

I use cv.CaptureFromCAM in a Django app, but my script block a this command.Without Django, it works and I can see my webcam turns on.
Here's my script :
import cv, Image
def takePhoto():
"""Return a PIL img"""
print "Taking photo"
cv_img = cv.QueryFrame( cv.CaptureFromCAM(0) )
pil_img = Image.fromstring("L", cv.GetSize(cv_img), cv_img.tostring())
return pil_img
If someone know why I can't use a method like cv.CaptureFromCAM in Django's scripts ?
PS : I already tried to decompose in several lines...

Resolved :
I put cv.CaptureFromCAM in a var settings.py for launch it at website start up.
I access to that var for take a photo, example :
In settings.py:
CAM = cv.CaptureFromCAM(0)
In views.py:
from django.http import HttpResponse
import cv, Image
def instantPhoto(request) :
cv_img = cv.QueryFrame( CAM[0] )
pil_img = Image.fromstring("RGB", cv.GetSize(cv_img), cv_img.tostring())
response = HttpResponse(mimetype="image/png")
pil_img.save(response, "PNG")
return response

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 output my images into html documents using python (Django)

please i need help with my django project. The code i have here is taking screenshots and saving it in my media folder so i want to output the pictures in my html page but it's giving me issues, i think i'm missing a lot.
Here is my python code which is taking the screenshots
from django.http import HttpResponse
import time,random,pyautogui
from django.db import models
import sys,os
from shots.models import pictures
from shots.forms.forms import DocumentForm
from django.conf import settings
def button(request):
return render(request,'index.html')
def output(request):
while True:
myScreenshot = pyautogui.screenshot()
name = random.randrange(1,1000)
full_name = str(name) + ".jpg"
filepath = settings.MEDIA_ROOT + '\shots'
full_path = filepath + full_name
saver = myScreenshot.save(full_path)
# generate a random time between 120 and 300 sec
random_time = random.randrange(3,6)
# wait between 120 and 300 seconds (or between 2 and 5 minutes)
time.sleep(random_time)
myScreenshots2 = []
myScreenshots2.append(saver)
# return (myScreenshots2)
return HttpResponse(request,'task.html',saver)
def stopshot(request):
os.system("pause")```
Python code runs on the server, and user is using a client to connect to the server.When you want to take screenshots it should be done by client not the server, since server is not users computer.
Check out this question to see how you can take screenshots from client using js.

In python, how do I get urllib to recognize multiple lines in a string as separate URLs?

I'm very new to code so forgive any errors I make in explanation! I'm trying to write code on python that uses Praw to access the /r/pics subreddit, scrape the source urls and display them with urllib, cv2 and numpy.
Currently my code looks like this:
import praw
import numpy as np
import urllib
import cv2
# urllib set-up
def reddit_scrape(url):
resp = urllib.request.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
# reddit set-up
reddit = praw.Reddit(client_id = 'id',
client_secret = 'secret',
user_agent = 'agent')
subreddit = reddit.subreddit('pics')
hot_pics = subreddit.hot(limit=10)
for submission in hot_pics:
if not submission.stickied:
print(submission.url)
# print images
urls = [submission.url]
for url in urls:
image = reddit_scrape(url)
cv2.imshow('image', image)
cv2.waitKey(0)
My problem when I run this is that although the print(submission.url) line prints a full list of the top 10 posts, only the last url on the list is actually opened and displayed.
My guess is that the error lies somewhere in my definition of
urls = [submission.url]
But I can't define 'urls' to be a static list of urls, because the hot list changes over time.
What am I doing wrong? is there even a right way to do this? Any help would be greatly appreciated.
submission is whatever the last submission was at the end of your for loop. Instead of constructing urls outside the loop, so when you say urls = [submission.url] you're only getting the last url. Instead you should create a list and append them:
urls = []
for submission in hot_pics:
if not submission.stickied:
urls.append(submission.url)
Or even the more Pythonic:
urls = [submission.url for submission in hot_pics if not submission.stickied]
Then the for url in urls will loop through all the appended urls.

Odoo8. Upload product image programmatically

I get an image from url and try to upload it to Odoo (product.template, image column). I tried many methods to do that but none of them helped me. Could you give me the right way to upload image of product to Odoo without using csv import.
This worked for me :
import urllib2
import base64
image = urllib2.urlopen('http://ddd.com/somepics.jpg').read()
image_base64 = base64.encodestring(image)
product.image_medium = image_base64 //(new api v9)
#in old api maybe something like
#prod_obj.write(prod_id, {'image_medium': image_base64})
you may need something like this
using a psycopg2 library
try:
logo = urllib2.urlopen(logo_url).read()
except:
print 'waitting 60s'
time.sleep(60)
logo = urllib2.urlopen(logo_url).read()
res_data={'image':psycopg2.Binary(logo)}
...
If you have image URL and need to set in product then you can do as following and call this method when install/upgrade your custom module.
import requests
import base64
#api.multi
def get_image(self):
for product in self:
img = False
if image.url:
response = requests.get(image.url)
if response.ok and response.content :
img = base64.b64encode(response.content)
else :
img = False
product.image = img

GAE python display multiple images in on page

I'm trying to display multiple images (pulled from datastore) in one page.
Doing this only displays 1 image...
class Stocks(db.Model):
ticker = db.StringProperty()
picture = db.BlobProperty(default=None)
What i use to serve:
self.response.headers['Content-Type'] = 'image/jpeg'
self.response.out.write(stock.picture)
Is this the only way i can server the picture?
Can i do it in a way where i do multiple image response outs?
Something along the lines like this.
self.response.out.write('<img src=' + stock.picture + '>')
UPDATE: Thanks for the reply. Totally didn't know you could do something like that.
So i did this:
app = webapp2.WSGIApplication([('/dailystocks', frontend_dailyStocks),('/image/.*', ServeImage),('/mainPage', MainPage)], debug=True)
Then this:
class MainPage(webapp2.RequestHandler):
def get(self):
images = Stocks.all().fetch(100)
html = ['<img src="/image/%s" />' % img.key() for img in images]
self.response.out.write(html)
class ServeImage(webapp2.RequestHandler):
def get(self):
key = self.request.get('key')
image = Stocks.get(key)
if image:
self.response.headers['Content-Type'] = 'image/jpeg'
self.response.out.write(image.picture)
else:
self.abort(404)
The thing loaded but it showed a list of broken image links.
This is an example image link:
http://*****.appspot.com/image/ag9zfmpwZ2V0bGlzdGluZ3NyEwsSBlN0b2NrcxiAgICAwOGGCAw
For each picture you want to serve, you'll need a separate HTTP call. So you may write a handler to serve an image, much like you suggested, as follows:
class ServeImage(webapp2.RequestHandler):
def get(self):
key = self.request.get('key')
image = Stocks.get(key)
if image:
self.response.headers['Content-Type'] = 'image/jpeg'
self.response.out.write(image.picture)
else:
self.abort(404)
Then in your main handler, load the images and render the html, referencing the ServeImage handler in each img tag ...
class MainPage(webapp2.RequestHandler):
def get(self):
images = Stocks.all().fetch(100)
html = ['<img src="/image?key=%s" />' % img.key() for img in images]
self.response.out.write(html)
You'll need to route the url /image to your ServeImage handler.

Categories

Resources