Skip to content

Instantly share code, notes, and snippets.

@ashitani
Created December 29, 2021 14:44
Show Gist options
  • Save ashitani/7de2e1cdce911c7c6ac0290f483ed69b to your computer and use it in GitHub Desktop.
Save ashitani/7de2e1cdce911c7c6ac0290f483ed69b to your computer and use it in GitHub Desktop.
DearPyGUIとOpenCVのテスト。中央付近の平均値をプロットするようにした。
import dearpygui.dearpygui as dpg
import array
import cv2
import numpy as np
image_width = 320
image_height = 180
average_rect = (60,120,120,200) # y0,y1,x0,x1
def update_image(img):
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGBA)
img = img.astype(np.float32)/255.0
dpg.set_value("image_tag", img.flatten())
dmax=500
data_x=np.linspace(0,dmax-1,dmax)
data_r=np.zeros(dmax)
data_g=np.zeros(dmax)
data_b=np.zeros(dmax)
def push_data(data, newdata):
global dmax
data[:dmax-1] =data[1:dmax]
data[dmax-1]=newdata
return data
def update_plot(img):
global data_x,data_r
roi=img[average_rect[0]:average_rect[1],average_rect[2]:average_rect[3],:]
# img is opencv BGR image
b=roi[:,:,0]
g=roi[:,:,1]
r=roi[:,:,2]
push_data(data_r, np.average(r))
push_data(data_g, np.average(g))
push_data(data_b, np.average(b))
dpg.set_value('plot_r_tag', [data_x, data_r])
dpg.set_value('plot_g_tag', [data_x, data_g])
dpg.set_value('plot_b_tag', [data_x, data_b])
def setup():
dpg.create_context()
img = np.zeros( (image_height,image_width,4), dtype=np.float32)
with dpg.texture_registry(show=False):
h,w,c = img.shape
dpg.add_raw_texture(w,h, img, format=dpg.mvFormat_Float_rgba, tag="image_tag")
with dpg.window(label="Image", no_resize=True,pos=(20,0)):
dpg.add_image("image_tag")
with dpg.window(label="Statistics", no_resize=True,pos=(20,200)):
with dpg.plot( height=160, width=320):
dpg.add_plot_legend()
dpg.add_plot_axis(dpg.mvXAxis, label="")
dpg.set_axis_ticks(dpg.last_item(),())
dpg.add_plot_axis(dpg.mvYAxis, label="average", tag="y_axis")
dpg.set_axis_limits("y_axis", 0, 255)
dpg.add_line_series(data_x, data_b, label="B", parent="y_axis", tag="plot_b_tag")
dpg.add_line_series(data_x, data_r, label="R", parent="y_axis", tag="plot_r_tag")
dpg.add_line_series(data_x, data_g, label="G", parent="y_axis", tag="plot_g_tag")
dpg.create_viewport(title='OpenCV and DearPyGui', width=400, height=400,resizable=False)
dpg.setup_dearpygui()
dpg.show_viewport()
def main():
setup()
capture = cv2.VideoCapture(1)
while dpg.is_dearpygui_running():
ret, img = capture.read()
if(ret):
img = cv2.resize(img,(image_width,image_height))
update_plot(img)
img = cv2.rectangle(img,(average_rect[2],average_rect[0]),(average_rect[3],average_rect[1]),(0,0,255),2)
update_image(img)
dpg.render_dearpygui_frame()
dpg.destroy_context()
if __name__ == '__main__':
main()
@ashitani
Copy link
Author

ashitani commented Dec 29, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment