How to solve a zero division error in an opencv function in django views?
I'm trying to find the center of contours using an opencv function and then take those points and plot them. My main problem is that the opencv function keeps giving me a zero division error. The code is as follows:
def Contours(request):
filename="C:/Users/ishraq/Downloads/traffic2.mp4"
cv2.ocl.setUseOpenCL(False) #get rid of error:(-215) The data should normally be NULL! in function
NumpyAllocator::allocate
vidcap = cv2.VideoCapture(filename)
fgbg = cv2.createBackgroundSubtractorMOG2()
while(vidcap.isOpened()):
success, frame = vidcap.read()
fgray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
fgmask = fgbg.apply(fgray)
ret,fgmaskthresh = cv2.threshold(fgmask,127,255,0)
_, contours, hierarchy = cv2.findContours(fgmaskthresh.copy(),1,2)
mask = np.zeros(fgray.shape, np.uint8)
count=0;
for contour in contours:
count=count+1
cnt=contours[0]
M=cv2.moments(cnt)
cX = float(M['m10'] / M['m00'])
cY = float(M['m01'] / M['m00'])
cv2.drawContours(mask,contours,-1,(255,100,100),1)
cv2.imshow('frame',fmaskthresh)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
vidcap.release()
cv2.destroyAllWindows()
return render_to_response("app/VideoPlayer.html",{'Cx':cX,'Cy':cY})
I looked at the stack trace and found that the cX and cY values are always 0. I can't figure as to what is going wrong that my code is defaulting the two variables to zero. How do I solve this so that my cX and cY variables don't default to 0?
/r/django
https://redd.it/6bjzx6
I'm trying to find the center of contours using an opencv function and then take those points and plot them. My main problem is that the opencv function keeps giving me a zero division error. The code is as follows:
def Contours(request):
filename="C:/Users/ishraq/Downloads/traffic2.mp4"
cv2.ocl.setUseOpenCL(False) #get rid of error:(-215) The data should normally be NULL! in function
NumpyAllocator::allocate
vidcap = cv2.VideoCapture(filename)
fgbg = cv2.createBackgroundSubtractorMOG2()
while(vidcap.isOpened()):
success, frame = vidcap.read()
fgray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
fgmask = fgbg.apply(fgray)
ret,fgmaskthresh = cv2.threshold(fgmask,127,255,0)
_, contours, hierarchy = cv2.findContours(fgmaskthresh.copy(),1,2)
mask = np.zeros(fgray.shape, np.uint8)
count=0;
for contour in contours:
count=count+1
cnt=contours[0]
M=cv2.moments(cnt)
cX = float(M['m10'] / M['m00'])
cY = float(M['m01'] / M['m00'])
cv2.drawContours(mask,contours,-1,(255,100,100),1)
cv2.imshow('frame',fmaskthresh)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
vidcap.release()
cv2.destroyAllWindows()
return render_to_response("app/VideoPlayer.html",{'Cx':cX,'Cy':cY})
I looked at the stack trace and found that the cX and cY values are always 0. I can't figure as to what is going wrong that my code is defaulting the two variables to zero. How do I solve this so that my cX and cY variables don't default to 0?
/r/django
https://redd.it/6bjzx6
reddit
How to solve a zero division error in an opencv... • r/django
I'm trying to find the center of contours using an opencv function and then take those points and plot them. My main problem is that the opencv...
[Ask Flask] [Flask-SQLAlchemy] [Flask-RESTful] Is it possible to implicitly define a model's column? Want to permit POST requests with *args parameter. Can SQLAlchemy dynamically generate columns?
Hi r/Flask!
I'm creating a RESTful API that returns a list of cocktail ideas based on an input of ingredients. Right now I'm trying to figure out how to store multiple ingredients per row.
Here's my Cocktail resource class. Looking for advice. I thought about creating a separate table for ingredients, but how would I relate that back to the Cocktail table? Foreign key? Little lost here!
Thanks!
from flask_restful import Resource, reqparse
from flask_jwt import jwt_required
from models.cocktail import CocktailModel, IngredientModel
class Cocktail(Resource):
parser = reqparse.RequestParser()
parser.add_argument('name',
type=str,
required=True,
help="This field cannot be left blank")
parser.add_argument('instructions',
type=str,
required=True
help="This field cannot be left blank")
parser.add_argument('ingredients', action='append',
type=str,
required=True,
help="This field cannot be left blank")
def get(self, *ingredients):
#GET json of drinks based on ingredient args
@jwt_required()
def post(self, name, instructions, *ingredients):
# CREATE a drink
# add check if drink already exists
data = Cocktail.parser.parse_args()
cocktail = CocktailModel(name, data['ingredients'],
data['instructions'], data['ingredients'])
try:
cocktail.save_to_db()
except:
return {"message": "An error occured inserting the item."}, 500
return item.json(), 201
/r/flask
https://redd.it/6uke6q
Hi r/Flask!
I'm creating a RESTful API that returns a list of cocktail ideas based on an input of ingredients. Right now I'm trying to figure out how to store multiple ingredients per row.
Here's my Cocktail resource class. Looking for advice. I thought about creating a separate table for ingredients, but how would I relate that back to the Cocktail table? Foreign key? Little lost here!
Thanks!
from flask_restful import Resource, reqparse
from flask_jwt import jwt_required
from models.cocktail import CocktailModel, IngredientModel
class Cocktail(Resource):
parser = reqparse.RequestParser()
parser.add_argument('name',
type=str,
required=True,
help="This field cannot be left blank")
parser.add_argument('instructions',
type=str,
required=True
help="This field cannot be left blank")
parser.add_argument('ingredients', action='append',
type=str,
required=True,
help="This field cannot be left blank")
def get(self, *ingredients):
#GET json of drinks based on ingredient args
@jwt_required()
def post(self, name, instructions, *ingredients):
# CREATE a drink
# add check if drink already exists
data = Cocktail.parser.parse_args()
cocktail = CocktailModel(name, data['ingredients'],
data['instructions'], data['ingredients'])
try:
cocktail.save_to_db()
except:
return {"message": "An error occured inserting the item."}, 500
return item.json(), 201
/r/flask
https://redd.it/6uke6q
reddit
[Ask Flask] [Flask-SQLAlchemy] [Flask-RESTful] Is it... • r/flask
Hi r/Flask! I'm creating a RESTful API that returns a list of cocktail ideas based on an input of ingredients. Right now I'm trying to figure out...
Help with using public APIs
Edit-
day=datetime.datetime.today().strftime('%Y-%m-%d')#Get Todays Date, Daily Setting
my problem is below this
url = "https://demo.docusign.net/restapi/v2/accounts/"+accountId+"/envelopes"
querystring = {"from_date":Date,"status":"completed"}#if Envelope is completed
headers = { 'X-DocuSign-Authentication': "{\"Username\":\""+ email +"\",\"Password\":\""+Password+"\",\"IntegratorKey\": \""+IntegratorKey+"\"}", 'Content-Type': "application/json", 'Cache-Control': "no-cache", 'Postman-Token': "e53ceaba-512d-467b-9f95-1b89f6f65211" }
**my problem above this **
''' Envelope Response ''' response = requests.request("GET", url, headers=headers, params=querystring) envelopes=response.text
I currently have a python 3 program on my desktop. I run it with idle and everything is how I want it. What I want to do with Django is use this code to print its outputs on a webpage and have the user download it’s additional csv file output. I have managed to make a Django localhost and I am stuck at that point. I do not know how to use my python 3 code to run to webpage. The code is made up of api calls , I use postman to help me with sending the right parameters. I will add a example of code. All I want is for user to enter value such as “accountID” so that the api can complete the request and give them data for their own request. I would highly appreciate help on this
I have been trying for hours, from my understanding I have to make a view then send to HTML template
/r/django
https://redd.it/8ri846
Edit-
day=datetime.datetime.today().strftime('%Y-%m-%d')#Get Todays Date, Daily Setting
my problem is below this
url = "https://demo.docusign.net/restapi/v2/accounts/"+accountId+"/envelopes"
querystring = {"from_date":Date,"status":"completed"}#if Envelope is completed
headers = { 'X-DocuSign-Authentication': "{\"Username\":\""+ email +"\",\"Password\":\""+Password+"\",\"IntegratorKey\": \""+IntegratorKey+"\"}", 'Content-Type': "application/json", 'Cache-Control': "no-cache", 'Postman-Token': "e53ceaba-512d-467b-9f95-1b89f6f65211" }
**my problem above this **
''' Envelope Response ''' response = requests.request("GET", url, headers=headers, params=querystring) envelopes=response.text
I currently have a python 3 program on my desktop. I run it with idle and everything is how I want it. What I want to do with Django is use this code to print its outputs on a webpage and have the user download it’s additional csv file output. I have managed to make a Django localhost and I am stuck at that point. I do not know how to use my python 3 code to run to webpage. The code is made up of api calls , I use postman to help me with sending the right parameters. I will add a example of code. All I want is for user to enter value such as “accountID” so that the api can complete the request and give them data for their own request. I would highly appreciate help on this
I have been trying for hours, from my understanding I have to make a view then send to HTML template
/r/django
https://redd.it/8ri846
[AF] My form data is showing up in the textarea <wrapped in brackets like this> and I don't know how to resolve
Hi all,
Obviously I'm new at this. I have a form. I send it data like so via the route:
@app.route('/edit_log/<postId>', methods=['GET', 'POST'])
@login_required
def edit_log(postId):
#get the data from the database to show in the form
postData = Post.query.filter_by(id=postId).first()
form = EditPostForm()
if form.validate_on_submit():
post = Post(body=form.post.data, author=current_user)
db.session.commit()
flash('Your changes have been saved.')
return redirect(url_for('org'))
elif request.method == 'GET':
#fill the form data with the actual post info from the above query
form.post.data = postData
return
/r/flask
https://redd.it/a7ivpg
Hi all,
Obviously I'm new at this. I have a form. I send it data like so via the route:
@app.route('/edit_log/<postId>', methods=['GET', 'POST'])
@login_required
def edit_log(postId):
#get the data from the database to show in the form
postData = Post.query.filter_by(id=postId).first()
form = EditPostForm()
if form.validate_on_submit():
post = Post(body=form.post.data, author=current_user)
db.session.commit()
flash('Your changes have been saved.')
return redirect(url_for('org'))
elif request.method == 'GET':
#fill the form data with the actual post info from the above query
form.post.data = postData
return
/r/flask
https://redd.it/a7ivpg
reddit
r/flask - [AF] My form data is showing up in the textarea and I don't know how to resolve
1 vote and 1 comment so far on Reddit
Creating a webp image on post_save
Hi everyone,
I've figured out how to create a webp image in my /media/ folder within the correct directory. Now, I'm needing to save this image to a field that i've crated on my model.
def create_webp_image(sender, instance, *args, **kwargs):
image_url = instance.image.thumbnail['1920x1080'].url
path = "http://localhost:8000" + image_url
response = requests.get(path, stream=True)
img = Image.open(BytesIO(response.content))
#build filepath
position = path.rfind("/") + 1
newpath2 = path[0:position].split('/media/')[1]
#get name of file (eg. picture.webp)
name_of_file = path[position:].split('.')[0] + ".webp"
#get directory
image_dir = os.path.join(settings.MEDIA_ROOT, '')
/r/django
https://redd.it/1005ij1
Hi everyone,
I've figured out how to create a webp image in my /media/ folder within the correct directory. Now, I'm needing to save this image to a field that i've crated on my model.
def create_webp_image(sender, instance, *args, **kwargs):
image_url = instance.image.thumbnail['1920x1080'].url
path = "http://localhost:8000" + image_url
response = requests.get(path, stream=True)
img = Image.open(BytesIO(response.content))
#build filepath
position = path.rfind("/") + 1
newpath2 = path[0:position].split('/media/')[1]
#get name of file (eg. picture.webp)
name_of_file = path[position:].split('.')[0] + ".webp"
#get directory
image_dir = os.path.join(settings.MEDIA_ROOT, '')
/r/django
https://redd.it/1005ij1
reddit
Creating a webp image on post_save
Hi everyone, I've figured out how to create a webp image in my /media/ folder within the correct directory. Now, I'm needing to save this image...
blackjack from 100 days of python code.
Wow. This was rough on me. This is the 3rd version after I got lost in the sauce of my own spaghetti code. So nested in statements I gave my code the bird.
Things I learned:
write your pseudo code. if you don't know **how** you'll do your pseudo code, research on the front end.
always! debug before writing a block of something
if you don't understand what you wrote when you wrote it, you wont understand it later. Breakdown functions into something logical, then test them step by step.
good times. Any pointers would be much appreciated. Thanks everyone :)
from random import randint
import art
def checkscore(playerlist, dealerlist): #get win draw bust lose continue
if len(playerlist) == 5 and sum(playerlist) <= 21:
return "win"
elif sum(playerlist) >= 22:
return "bust"
elif sum(playerlist) == 21 and not sum(dealerlist)
/r/Python
https://redd.it/1i8xqld
Wow. This was rough on me. This is the 3rd version after I got lost in the sauce of my own spaghetti code. So nested in statements I gave my code the bird.
Things I learned:
write your pseudo code. if you don't know **how** you'll do your pseudo code, research on the front end.
always! debug before writing a block of something
if you don't understand what you wrote when you wrote it, you wont understand it later. Breakdown functions into something logical, then test them step by step.
good times. Any pointers would be much appreciated. Thanks everyone :)
from random import randint
import art
def checkscore(playerlist, dealerlist): #get win draw bust lose continue
if len(playerlist) == 5 and sum(playerlist) <= 21:
return "win"
elif sum(playerlist) >= 22:
return "bust"
elif sum(playerlist) == 21 and not sum(dealerlist)
/r/Python
https://redd.it/1i8xqld
Reddit
From the Python community on Reddit
Explore this post and more from the Python community
What could I have done better here?
Hi, I'm pretty new to Python, and actual scripting in general, and I just wanted to ask if I could have done anything better here. Any critiques?
import time
import colorama
from colorama import Fore, Style
color = 'WHITE'
colorvar2 = 'WHITE'
#Reset colors
print(Style.RESETALL)
#Get current directory (for debugging)
#print(os.getcwd())
#Startup message
print("Welcome to the ASCII art reader. Please set the path to your ASCII art below.")
#Bold text
print(Style.BRIGHT)
#User-defined file path
path = input(Fore.BLUE + 'Please input the file path to your ASCII art: ')
color = input('Please input your desired color (default: white): ' + Style.RESETALL)
#If no ASCII art path specified
if not path:
print(Fore.RED +
/r/Python
https://redd.it/1p4ffmh
Hi, I'm pretty new to Python, and actual scripting in general, and I just wanted to ask if I could have done anything better here. Any critiques?
import time
import colorama
from colorama import Fore, Style
color = 'WHITE'
colorvar2 = 'WHITE'
#Reset colors
print(Style.RESETALL)
#Get current directory (for debugging)
#print(os.getcwd())
#Startup message
print("Welcome to the ASCII art reader. Please set the path to your ASCII art below.")
#Bold text
print(Style.BRIGHT)
#User-defined file path
path = input(Fore.BLUE + 'Please input the file path to your ASCII art: ')
color = input('Please input your desired color (default: white): ' + Style.RESETALL)
#If no ASCII art path specified
if not path:
print(Fore.RED +
/r/Python
https://redd.it/1p4ffmh
Reddit
From the Python community on Reddit
Explore this post and more from the Python community