我在tkinter中做了一个代码,当我按下“开始”按钮时,相机打开并检测蓝色,当我按下“停止”按钮时,相机关闭。它第一次工作,但第二次,它不工作。我只是读了一些问题,它说我必须使用.place_forget()
来关闭相机,我使用,但是当我想让相机第二次打开时,它不工作了。下面是我的代码:
def color():
global video
video=cv2.VideoCapture(1)
ret, frame = video.read()
if ret == True:
frameHSV = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
frame=cv2.cvtColor(frame,cv2.COLOR_RGB2BGR)
mask = cv2.inRange(frameHSV,azulBajo,azulAlto)
contornos, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for c in contornos:
area = cv2.contourArea(c)
if area > 3000:
M = cv2.moments(c)
if (M["m00"]==0): M["m00"]=1
x = int(M["m10"]/M["m00"])
y = int(M['m01']/M['m00'])
cv2.circle(frame, (x,y), 7, (0,255,0), -1)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame, '{},{}'.format(x,y),(x+10,y), font, 0.75,(0,255,0),1,cv2.LINE_AA)
nuevoContorno = cv2.convexHull(c)
cv2.drawContours(frame, [nuevoContorno], 0, (255,0,0), 3)
img=Image.fromarray(frame)
image=ImageTk.PhotoImage(img)
lblVideo.configure(image=image)
lblVideo.image=image
lblVideo.after(1,color)
def quitar():
global video
lblVideo.place_forget()
video.release()
boton2=Button(frame1,width=5, font = ('Arial',14, 'bold'), text='Inciar', bg='yellow',bd=5, command=color)
boton2.place(x=85, y=210)
boton3=Button(frame1,width=5, font = ('Arial',14, 'bold'), text='Parar', bg='yellow',bd=5, command=quitar)
boton3.place(x=290, y=210)
1条答案
按热度按时间carvr3hs1#
您不应在
color()
内调用video = cv2.VideoCapture(1)
。因此,您需要创建另一个由 “Inciar” 按钮调用的函数,然后创建video
并在此函数内调用color()
。此外,
lblVideo.after(...)
之前的四行应该位于if
块内。以下是更新后的代码: