How to increase my container width to accomodate more items - plotly-dash

I am building a dashboard using Plotly Dash. I am using bootstrap.min.css , I would like to increase the width of my container so that I can accommodate two graphs , in a single row.
My second graphs(Line graph) , has more width hence unable to align them in a single row.
I have attached the snapshot below,
DASH UI CODE :
# the style arguments for the sidebar. We use position:fixed and a fixed width
SIDEBAR_STYLE = {
"top": 0,
"left": 0,
"bottom": 0,
"width": "16rem",
"padding": "2rem 1rem",
"background-color": "#f8f9fa",
"position": "fixed",
"color":"#000",
}
# the styles for the main content position it to the right of the sidebar and
# add some padding.
CONTENT_STYLE = {
"margin-left": "18rem",
"margin-right": "2rem",
"padding": "2rem 1rem",
}
sidebar = html.Div(
[
html.H2("Plate", className="display-4"),
html.Hr(),
html.P(
"A simple dashboard", className="lead"
),
dbc.Nav(
[
dbc.NavLink("Dashboard", href="/dashboard", id="page-1-link"),
dbc.NavLink("Analytics", href="/page-2", id="page-2-link"),
dbc.NavLink("Page 3", href="/page-3", id="page-3-link"),
html.Hr(),
dbc.NavLink("Logout", href="/logout", id="page-4-link"),
],
vertical=True,
pills=True,
),
],
style=SIDEBAR_STYLE,
)
content = html.Div(id='page-content' , className ='container' ,style=CONTENT_STYLE)
app.layout = html.Div([dcc.Location(id="url"), sidebar, content])
app.config.suppress_callback_exceptions = True
# this callback uses the current pathname to set the active state of the
# corresponding nav link to true, allowing users to tell see page they are on
#app.callback(
[Output(f"page-{i}-link", "active") for i in range(1, 4)],
[Input("url", "pathname")],
)
def toggle_active_links(pathname):
if pathname == "/" or pathname == "/dashboard":
# Treat page 1 as the homepage / index
return True, False, False
return [pathname == f"/page-{i}" for i in range(1, 4)]
#app.callback(Output("page-content", "children"), [Input("url", "pathname")])
def render_page_content(pathname):
if pathname in ["/", "/page-1", "/dashboard"]:
dashBoard = html.Div([
html.Div([dcc.DatePickerRange(
id='my-date-picker-range',
min_date_allowed=dt(minDate[0],minDate[1],minDate[2]),
max_date_allowed=dt(maxDate[0],maxDate[1],maxDate[2]),
initial_visible_month=dt(maxDate[0],maxDate[1],maxDate[2]),
start_date=dt(minDate[0],minDate[1],minDate[2]).date(),
end_date=dt(maxDate[0],maxDate[1],maxDate[2]).date()
),
html.Button(id="date-button" , children ="Analyze" , n_clicks = 0, className = 'btn btn-outline-success')
], className = 'row'),
html.Div([
html.Br(),
html.Div([
html.H4(['Category Overview'] , className = 'display-4'),
html.Br(),
html.Br(),
], className = 'row'),
html.Div([
html.Div([dcc.Graph(id='categoryPerformance',figure = dict(data=ge.returnCategoryOverviewBarGraph(df)[0],
layout=ge.returnCategoryOverviewBarGraph(df)[1]))
], className = 'col'),
html.Div([dcc.Graph(id='categoryPerformanceTrend')
], className = 'col')
], className = 'row'),
html.Hr(),
html.Div([
html.Div([
dcc.Dropdown(id = 'category-dd', options = category_items, value = 'Food')
], className = 'col-6 col-md-4'),
html.Div([
dcc.Slider(id = 'headCount' , min = 5, max=20 , step = 5 , value = 5, marks = {i: 'Count {}'.format(i) for i in range(5,21,5)})
], className = 'col-12 col-sm-6 col-md-8')
], className = 'row'),
html.Div([
html.Br(),
html.Br(),
html.Div([
dcc.Graph(id ='idvlCategoryPerformanceBest')
], className ='col'),
html.Div([
dcc.Graph(id ='idvlCategoryPerformanceLeast')
], className = 'col')
], className = 'row')
])
] , className='container')
return dashBoard
I have zero knowledge in frontend / css , any help is much appreciated. Thanks !

Related

How to connect HTML elements with Dash Callback in Python

I'm using both html elements and dash bootstrap components in my code and wonder if I can connect an HTML component with a Dash component in callback. For example, I have a dash dropdown menu and want to update the html text based on the input of the dropdown menu.
#dropdown
html.Div =(
[
dcc.Dropdown(
id="dropdown",
options=[
{"label": "option1", "value": "option1"},
{"label": "option2", "value": "option2"},
],
multi=True,
)
]
)
# HTML Components
html.Div =(
[
html.H2("The selected option is")
html.P(id="text-holder", children =["text"])
]
)
#app.callback(
Output("text-holder", "children"),
Input("dropdown", "value)
)
def fill_text(value):
return value
Once a user selects a value from the dropdown menu, I want the selected value to appear on the text line created by html.P. For example, if "option1" is selected from the dropdown menu, the text that appears on the HTML part should be also "option1".
If I run the current script, I don't get any error message but the html part doesn't get updated at all. I think the callback is incorrect but am not sure how to fix it.
Using html.Div =( ... alters the value of html.Div. And it's really important to get the layout right.
Perhaps this is what you're looking for:
from dash import dcc, html, Dash, Output, Input
app = Dash(__name__)
app.layout = html.Div(
[
# dropdown
html.Div(
[
dcc.Dropdown(
id="dropdown",
options=[
{"label": f"option{idx}", "value": f"option{idx}"}
for idx in range(1, 5)
],
multi=True,
value="not specified",
)
]
),
# HTML Components
html.Div([html.H2("The selected option is"), html.P(id="text-holder")]),
]
)
#app.callback(Output("text-holder", "children"), Input("dropdown", "value"))
def fill_text(value):
return value
if __name__ == "__main__":
app.run_server()

Getting Dash longcallback details

just beginning with Dash 2.0 from plotly. Mainly to take advantage of longcallbacks. I try to get callback's id without success (i.e. the id I see in the worker when executing long call). Also struggling to get its state, ready(), successful() etc.
What I've got so far:
#app.long_callback(
output=Output("paragraph_id", "children"),
inputs=Input("button_id", "n_clicks"),
running=[
(Output("button_id", "disabled"), True, False),
(Output("cancel_button_id", "disabled"), False, True),
(
Output("paragraph_id", "style"),
{"visibility": "hidden"},
{"visibility": "visible"},
),
(
Output("progress_bar", "style"),
{"visibility": "visible"},
{"visibility": "hidden"},
),
],
cancel=[Input("cancel_button_id", "n_clicks")],
progress=[Output("progress_bar", "value"), Output("progress_bar", "max")],
prevent_initial_call=True
)
def update_progress(set_progress, n_clicks):
currentProgress = check_progress.delay()
i = 0
total = 15
while currentProgress.ready() == False:
time.sleep(1)
print("currentProgress.STATE")
print(currentProgress.state)
set_progress((str(i + 1), str(total)))
i += 1
return [f"Clicked {n_clicks} times" + " " + currentProgress.id]
#celery_app.task(bind=True)
def check_progress(self):
time.sleep(15)
return
I can manage to get these when executing celery task - check_progress(). How do I get id of update_progress() long callback?

Graph not showing

I have the following code
# -*- coding: utf-8 -*-
# # Two Pie Charts
import time
import dash
import dash_bootstrap_components as dbc
import plotly.express as px
import pandas as pd
from dash import Input, Output, dcc, html
# Data treatment
df = pd.read_csv('https://raw.githubusercontent.com/JorgeMiguelGomes/LEG2022_MediaMonitor/main/legislativas_2022_media_monitor_29jan2022/data_products/legislativas_2022_final_dataset_percentages.csv')
df_individuals = pd.read_csv('https://raw.githubusercontent.com/JorgeMiguelGomes/LEG2022_MediaMonitor/main/legislativas_2022_media_monitor_29jan2022/data_products/legislativas_2022_all_candidates_filtered.csv')
df_individuals = df_individuals.drop(columns=["Unnamed: 0"])
df_indivuduals = df_individuals.drop(columns=["Post Created Date"])
df_individuals_melt=pd.melt(df_individuals,id_vars=['candidato','Page Name'])
# Styling
pie_color_map = {
"Angry":"#EB9486",
"Love":"#CAE7B9"
}
app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP],suppress_callback_exceptions=True,
meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}],
)
app.layout = dbc.Container(
[
# First Row
dbc.Row(
[
dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#CAE7B9","opacity": "unset"}),width={'size':2}),
dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#F3DE8A","opacity": "unset"}),width={'size':2}),
dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#EB9486","opacity": "unset"}),width={'size':2}),
dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#7E7F9A","opacity": "unset"}),width={'size':2}),
dbc.Col(html.Hr(style={'borderWidth': "2vh", "width": "100%", "borderColor": "#97A7B3","opacity": "unset"}),width={'size':2}),
],className="g-0",
), # end of first row
dbc.Tabs(
[
dbc.Tab(label="About", tab_id="method", label_style={"color": "#CAE7B9"},tab_style={'background-color': '#97A7B3'},active_label_style={"background-color":"#080808"}),
dbc.Tab(label="Metrics by Totals", tab_id="totals", label_style={"color": "#F3DE8A"},tab_style={'background-color': '#7E7F9A'}, active_label_style={"background-color":"#080808"}),
dbc.Tab(label="Stacked Analysis", tab_id="stacked", label_style={"color": "#EB9486"},tab_style={'background-color': '#F3DE8A'}, active_label_style={"background-color":"#080808"}),
dbc.Tab(label="Love vs Angry", tab_id="love_angry", label_style={"color": "#7E7F9A"},tab_style={'background-color': '#EB9486'}, active_label_style={"background-color":"#080808"}),
dbc.Tab(label="Conclusions", tab_id="conclusions", label_style={"color": "#97A7B3"},tab_style={'background-color': '#F3DE8A'}, active_label_style={"background-color":"#080808"}),
],
id="tabs",
active_tab="love_angry", # this is the tab that will be active when the user comes to the website
), # end of tabs
html.Div(id="tab-content", className="p-5"),
]
)
# Callbacks
# Pie Chart for Candidates
# #app.callback(
# Output(component_id='graph_individuals', component_property='figure'),
# [Input(component_id='dropdown_candidates', component_property='value')],
# )
# def build_graph_individuals(column_chosen):
# dff = df
# totals_sentiment = dff.groupby(['candidato'])[['Love','Angry']].sum().reset_index()
# totals_sentiment_melt = pd.melt(totals_sentiment,id_vars="candidato")
# totals_sentiment_melt = totals_sentiment_melt[totals_sentiment_melt['candidato'] == column_chosen]
# fig_individuals = px.pie(totals_sentiment_melt,names="variable",values="value",hole=0.5, color="variable",color_discrete_map=pie_color_map)
# candidato_filter = column_chosen
# return fig_individuals
# Pie Chart for Media Outlets
#app.callback(
Output(component_id='graph_shares_comments', component_property='figure'),
Output(component_id='graph_individuals', component_property='figure'),
Input(component_id='dropdown_media_outlet', component_property='value'),
Input(component_id='dropdown_candidates', component_property='value')
)
def build_graphs(column_chosen, candidato_filter):
# Data Treatment for candidate graph
dff = df
totals_sentiment = dff.groupby(['candidato'])[['Love','Angry']].sum().reset_index()
totals_sentiment_melt = pd.melt(totals_sentiment,id_vars="candidato")
totals_sentiment_melt = totals_sentiment_melt[totals_sentiment_melt['candidato'] == column_chosen]
# Data Treatment for media graph
dff_m = df[df['candidato']== candidato_filter]
print(dff_m)
totals_sentiment_media = dff_m.groupby(['Page Name'])[['Love','Angry']].sum().reset_index()
totals_sentiment_media_melt = pd.melt(totals_sentiment_media,id_vars="Page Name")
totals_sentiment_media_melt = totals_sentiment_media_melt[totals_sentiment_media_melt['Page Name'] == column_chosen]
print("HELLO HELLO")
print(totals_sentiment_media_melt)
# Pice Charts
fig_candidates = px.pie(totals_sentiment_melt,names="variable",values="value",hole=0.5, color="variable",color_discrete_map=pie_color_map)
fig_media = px.pie(totals_sentiment_media_melt,names="variable",values="value",hole=0.6, color="variable",color_discrete_map=pie_color_map)
return fig_candidates, fig_media
# TABS CALLBACKS -------------------------------------
#app.callback(Output("tab-content", "children"),
[Input("tabs", "active_tab")])
def switch_tab(at):
if at == "love_angry":
tab4_content = dbc.Row(
[
dbc.Col(
[
dcc.Dropdown(
id='dropdown_candidates',
options=[{'label': i, 'value': i} for i in df_individuals_melt.candidato.unique()
],
optionHeight=35, #height/space between dropdown options
value='António Costa', #dropdown value selected automatically when page loads
disabled=False, #disable dropdown value selection
multi=False, #allow multiple dropdown values to be selected
searchable=True, #allow user-searching of dropdown values
search_value='', #remembers the value searched in dropdown
placeholder='Please select...', #gray, default text shown when no option is selected
clearable=True, #allow user to removes the selected value
style={'width':"100%"}, #use dictionary to define CSS styles of your dropdown
# className='select_box', #activate separate CSS document in assets folder
# persistence=True, #remembers dropdown value. Used with persistence_type
# persistence_type='memory' #remembers dropdown value selected until...
),
dbc.Col(
dcc.Graph(id='graph_individuals'),
),
],width={'size':6, 'offset':0}
),
dbc.Col(
[
dcc.Dropdown(
id='dropdown_media_outlet',
options=[{'label': i, 'value': i} for i in df['Page Name'].unique()
],
optionHeight=35, #height/space between dropdown options
value='Agência Lusa', #dropdown value selected automatically when page loads
disabled=False, #disable dropdown value selection
multi=False, #allow multiple dropdown values to be selected
searchable=True, #allow user-searching of dropdown values
search_value='', #remembers the value searched in dropdown
placeholder='Please select...', #gray, default text shown when no option is selected
clearable=True, #allow user to removes the selected value
style={'width':"100%"}, #use dictionary to define CSS styles of your dropdown
# className='select_box', #activate separate CSS document in assets folder
# persistence=True, #remembers dropdown value. Used with persistence_type
# persistence_type='memory' #remembers dropdown value selected until...
),
dbc.Col(
dcc.Graph(id='graph_shares_comments'),
),
],width={'size':6, 'offset':0}
),
],
),
return tab4_content
# Error Message
return html.P("FOR SUPPORT PURPOSES ONLY")
if __name__ == "__main__":
app.run_server(debug=True, port=8888)
The code is running without errors but as you can see in the image below, the chart on the left side is not rendering, and I'm totally lost.
I have inserted a print command in the script, and when I change the dropdowns the values change accordingly as they should.
However the pie chart remains empty, like it's not getting any information.
Maybe I've been looking at the same code for more hours than I should, and I'm missing something really simple, but I just can't spot it.
Any help would be really appreciated.
Disclosure This is not a commercial project nor will I use it in any commercial way.
You were filtering with the wrong keyword for totals_sentiment_melt, use this to correct it:
totals_sentiment_melt = totals_sentiment_melt[totals_sentiment_melt['candidato'] == candidato_filter]

dash_bootstrap_components Col and Row not showing as expected - just stacking each item

I am trying to build my first dash app and want to organize things using dbc.Col and dbc.Row. I'm trying to build something to look like this in the first tab section called "Equity Risk"...
basic layout i'm aiming for
Unfortunately, all that's returned on the first tab are 3 items vertically stacked on top of each other that each take up the full width of the screen.
This is my code so far - I'm not sure if this is enough code to diagnose the issue, but hopefully it is. I have double-checked the brackets/parenthesis, added width arguments to every column, and have googled similar things and still can't tell what's wrong. Any help would be much much appreciated!
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
auth = dash_auth.BasicAuth(app,USERNAME_PASSWORD_PAIRS)
server = app.server
# app layout
app.layout = html.Div([
# header banner with titles
html.Div(
children=[
html.H1('COMPANY NAME',
className="header-company-name"),
html.P('HISTORICAL EARNINGS SPREAD ANALYSIS', #'Historical earnings spread analysis',
className='header-page-name')
],
className="header-banner"
),
dcc.Tabs([
# THIS IS THE TAB THAT I'M TRYING TO ORGANIZE, BUT HAVE PROBLEMS WITH
dcc.Tab(label='Equity Risk', children=[
dbc.Container([
dbc.Row([
dbc.Col([
dbc.Row([
dbc.Col([
# user inputs and submit button
html.Div([
html.Div([
html.Div(children='User inputs',
className='block-title'),
html.Div(children='', className='title-line'),
html.Div(children='Enter a start and end date:',
className='input-title'),
dcc.DatePickerRange(id='my_date_range',
min_date_allowed=df.date.min(),
max_date_allowed=df.date.max(),
start_date=datetime(2007,1,1),
end_date=datetime.today()
)
],
),
html.Div(
children=[
html.Button(id='submit_button',
n_clicks=0,
children='Submit Inputs',
className='button')
],
)
],
# style={'width': '20%', 'display': 'inline-block', 'verticalAlign':'top'},
className='utilities-block'
)
], width=3)
]),
dbc.Row([
dbc.Col([
# checkbox
html.Div(
children=[
html.Div(children='Plot Adjustments',
className='block-title'),
html.Div(children='', className='title-line'),
dcc.RadioItems(id='plot_lines',
options=[
{'label':'Show mean and \u03C3 lines', 'value':'meanstd'},
{'label':'Show standard grid', 'value':'grid'}
],
value='meanstd',
labelStyle={'display':'block'},
inputClassName='radio-input',
labelClassName='radio-label')
],
# style={'width': '20%'},
className='utilities-block'
)
], width=3)
])
], width=3),
dbc.Col([
# graph
html.Div(
children=[
html.Div(children='Equity risk premium mainly between 15yr mean and -1\u03C3 in recent months',
className='block-title'),
html.Div(children='', className='title-line'),
dcc.Graph(id='my_graph',
figure=updated_figure,
style={'height': '83%'},
className='content-block')
],
# style={'width': '72%', 'display': 'inline-block', 'verticalAlign':'top', 'height':'450px'},
className='utilities-block'
)
], width=9)
]) # end of row
], fluid=True)
], style=tab_style, selected_style=tab_selected_style),
# IGNORE THIS TAB.. I HAVEN'T STARTED DOING ANY GRID LAYOUT YET
dcc.Tab(label='S&P vs P/E Ratio', children = [
html.Div(
children=[
html.Div(children='Spread between S&P price and P/E ratio is widening',
className='block-title'),
html.Div(children='', className='title-line'),
dcc.Graph(id='my_sp_pe_graph',
figure=sp_pe_figure,
style={'height': '90%'},
className='content-block')
],
style={'width': '75%', 'display': 'inline-block', 'verticalAlign': 'top', 'height': '550px',
'paddingLeft': '20px'},
className='utilities-block'
)
], style=tab_style, selected_style=tab_selected_style),
# dcc.Tab(label='Something Else', style=tab_style, selected_style=tab_selected_style)
], style=tabs_style)
])
The problem is caused by small width values for some Col elements. There is not enough horizontal space left to put elements next to each other which causes the elements to stack.
Basically what is happening is that the left part of the layout in the first tab has a column width of 3 and then the actual content is inside column elements which also have their width set to 3. If you inspect this part of the layout you will see that the width of this container is very small; the width is 1/16 of the row width.
So the solution is to either set the width of the inner most columns to 12 or to just use a regular div, since the outer column already only takes up 1/4 of the row width.

How to measure the difference between two frames given a set of pixel units for each frame?

I am using a dense optical flow algorithm in order to calculate the optical flow on a given video,
after I run the algorithm I receive the output bellow.
I would like to find a way to sum up the changes between two frames (or two sets of vectors (in pixel units)), meaning to find a numerical value to the change between frames in order to determine if these two frames are "similar" or "different"
this is the output (from what I understand, for each pixel it is the change x, y basically):
flow
[[[ 0.00080293 0.00456178]
[ 0.0023454 0.00762859]
[ 0.00337119 0.01088941]
...
[ 0.08646814 0.17195833]
[ 0.07680464 0.15070145]
[ 0.04990056 0.09711792]]
[[ 0.00197109 0.00610898]
[ 0.00431191 0.01074001]
[ 0.00629149 0.01567514]
...
[ 0.11541913 0.23083425]
[ 0.10006026 0.19827926]
[ 0.06407876 0.12646647]]
[[ 0.00333168 0.0071025 ]
[ 0.00625938 0.01281219]
[ 0.01047979 0.02093185]
...
[ 0.15598673 0.31461456]
[ 0.1284331 0.25725985]
[ 0.08006614 0.16013806]]
...
[[-0.11634359 0.09029744]
[-0.14934781 0.11287674]
[-0.24678642 0.17862432]
...
[ 0.00260158 0.00103487]
[ 0.00391656 0.00041338]
[ 0.00312206 0.00064316]]
[[-0.06021533 0.04847184]
[-0.07352059 0.05851178]
[-0.12553327 0.09319763]
...
[ 0.00314228 -0.00119414]
[ 0.00410303 -0.00139949]
[ 0.00334636 -0.00098234]]
[[-0.0192373 0.010998 ]
[-0.02326458 0.01555626]
[-0.04161371 0.02764582]
...
[ 0.00236979 -0.00039244]
[ 0.00327405 -0.00078911]
[ 0.00281549 -0.00057979]]]
flow
[[[-8.4514404e-03 -9.1092577e-03]
[-8.2096420e-03 -1.6217180e-02]
[-9.7641135e-03 -2.3235001e-02]
...
[ 8.4836602e-02 9.4629139e-02]
[ 7.0593305e-02 7.2248474e-02]
[ 6.2410351e-02 5.8204494e-02]]
[[-1.6573617e-02 -1.5174728e-02]
[-1.5833536e-02 -2.2253623e-02]
[-1.7538801e-02 -3.1138226e-02]
...
[ 1.3201687e-01 1.3085920e-01]
[ 1.1270510e-01 1.0012541e-01]
[ 1.0345179e-01 8.3722569e-02]]
[[-2.1787306e-02 -2.0292744e-02]
[-2.2391599e-02 -2.8152039e-02]
[-2.3549989e-02 -3.8980592e-02]
...
[ 1.5739001e-01 1.6933599e-01]
[ 1.3471533e-01 1.2855931e-01]
[ 1.2196152e-01 1.0327549e-01]]
...
[[-3.9006339e-03 -3.0767643e-03]
[-1.8084457e-02 -8.7532159e-03]
[-4.0460575e-02 -1.6521217e-02]
...
[ 5.4473747e-03 -1.9708525e-03]
[ 4.3195980e-03 -1.6532388e-03]
[ 2.4038905e-03 -2.6415614e-04]]
[[-2.2322503e-03 -3.0169063e-03]
[-1.1787469e-02 -8.9037549e-03]
[-2.8192652e-02 -1.6921449e-02]
...
[ 1.9799198e-03 -3.8150212e-04]
[ 1.5747466e-03 -5.4049061e-04]
[ 9.2306529e-04 -1.1204407e-04]]
[[-1.1798806e-03 -1.9108414e-03]
[-6.6612735e-03 -5.3157108e-03]
[-1.6056010e-02 -9.3358066e-03]
...
[ 4.8137631e-04 6.4036541e-04]
[ 3.4130082e-04 3.7227676e-04]
[ 1.7955518e-04 1.8480681e-04]]]...
this id the code we are using for the optical flow calculation:
def _calc_optical_flow_(distance_array):
cap = cv2.VideoCapture("videos/3.1.avi")
output_file_text = open("output.txt", "w+")
ret, frame1 = cap.read()
prvs = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
hsv = np.zeros_like(frame1)
frames_array.append(frame1)
hsv[..., 1] = 255
count = 0
distance = 0
while(1):
ret, frame2 = cap.read()
if frame2 is None:
break
frames_array.append(frame2)
next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(prvs, next, None, pyr_scale=0.5, levels=3, winsize=15, iterations=1,
poly_n=5, poly_sigma=1.2, flags=0)
mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
hsv[..., 0] = ang*180/np.pi/2
hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
if count == 10:
count = 0
output_file_text.write("flow\n")
output_file_text.write(np.array_str(flow) + "\n")
distance = function(flow, distance)
distance_array.append(distance)
#print ("flow",flow)
cv2.imshow('frame2',rgb)
count=count+1
k = cv2.waitKey(10) & 0xff
if k == 27:
break
elif k == ord('s'):
#cv2.imwrite('opticalfb.png', frame2)
#cv2.imwrite('opticalhsv.png', rgb)
prvs = next
output_file_text.close()
cap.release()
cv2.destroyAllWindows()
return distance_array