Problem about my snapshot program

Hi everyone,

i write a program with Tk and i want to take a snapshot from my csi camera with click “save” on my touch screen. Here is my source code:

import cv2
import tkinter as tk
import os
from uuid import uuid1
from tkinter import filedialog
from PIL import Image, ImageTk
import threading

save_dir = ‘dataset’

try:
os.makedirs(save_dir)
except FileExistsError:
print(‘Directories not created becasue they already exist’)

window = tk.Tk()
window.title(“Camera”)
sw = window.winfo_screenwidth()
sh = window.winfo_screenheight()
wx = 400
wh = 400
num = 0
window.geometry(“%dx%d+%d+%d” %(wx,wh,(sw-wx)/2,(sh-wh)/2-100))
canvas = tk.Canvas(window,bg=‘#c4c2c2’,height=wh,width=wx)
canvas.pack()

def gstreamer_pipeline(
capture_width=200,
capture_height=200,
display_width=200,
display_height=200,
framerate=30,
flip_method=0,
):
return (
"nvarguscamerasrc ! "
"video/x-raw(memory:NVMM), "
"width=(int)%d, height=(int)%d, "
"format=(string)NV12, framerate=(fraction)%d/1 ! "
"nvvidconv flip-method=%d ! "
"video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! "
"videoconvert ! "
“video/x-raw, format=(string)BGR ! appsink”
% (
capture_width,
capture_height,
framerate,
flip_method,
display_width,
display_height,
)
)

capture = cv2.VideoCapture(gstreamer_pipeline(flip_method=0), cv2.CAP_GSTREAMER)

def video_demo():
def cc():
while True:
ret, frame = capture.read()
frame = cv2.flip(frame, 1)
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image)
image_file=ImageTk.PhotoImage(img)
canvas.create_image(0,0,anchor= ‘nw’,image = image_file)
t=threading.Thread(target=cc)
t.start()

def snapshot():
global num
ret, img = capture.read()
num = num + 1
filename = os.path.join(save_dir, str(uuid1()) + ‘.jpg’)
cv2.imwrite(filename, img)
lb_picture_number.config(text= str(num))

bt_start = tk.Button(window,text=“Open Camera”,height=2,width=15,command=video_demo)
bt_start.place(x=100,y=300)
bt_snapshot = tk.Button(window,text=“Save”,height=2,width=15,command=snapshot)
bt_snapshot.place(x=100,y=350)
lb_picture_number = tk.Label(window, text=“0”,height=2,width=15)
lb_picture_number.place(x = 200, y = 350)

window.mainloop()

and i can sucessfully open the camera but when i click save there comes a problem:

(python3: 8428): Gstreamer-CRITICAL **:09:52;01.988: gst_mini_object_unref: assertion 'GST_MINI_OBJECT_REFCOUNT_VALUE(mini_object) > 0 'failed

and camera freezed then my GUI is dead.

Have a reference to below link for the openCV use case.