首页 > 解决方案 > 如何使用opencv Python tkinter为传送带上的计数对象添加参考线

问题描述

我正在尝试构建一个视觉系统,可以计算在变速传送带上移动的巧克力。使用 OpenCV 和 python。与此类似: 在此处输入图像描述

我尝试了 Stackoverflow 中提供的许多解决方案,但都没有帮助。关于这一点,我请求这个社区的专家帮助在下面的代码中实现帮助。

不知何故,我设法在 cv2.VideoCapture 的帮助下创建了一个 Tkinter GUI。

我附上的代码只有 Tkinter 窗口来显示视频源。我想添加代码,以便它在视频帧中显示参考线,如下图所示。

需要帮助部分: 1. 我想为视频帧实现一条参考线,以便当对象越过该线时,它会计算对象。

  1. 我如何分离斑点并提取各自的质心。

  2. 如果质心越过参考边界线,我必须增加计数变量。

代码:

import cv2
import tkinter as tk
from tkinter import *
from tkinter.ttk  import Frame
from PIL import Image, ImageTk

white       = "#ffffff"
lightBlue2  = "#adc5ed"
font        = "Constantia"
fontButtons = (font, 12)
maxWidth    = 800
maxHeight   = 480

#Graphics window
mainWindow = tk.Tk()
mainWindow.configure(bg=lightBlue2)
mainWindow.geometry('%dx%d+%d+%d' % (maxWidth,maxHeight,0,0))
mainWindow.resizable(0,0)
# mainWindow.overrideredirect(1)

mainFrame = Frame(mainWindow)
mainFrame.place(x=20, y=20)

#Capture video frames
lmain = tk.Label(mainFrame)
lmain.grid(row=0, column=0)

cap = cv2.VideoCapture(0)

def show_frame():
    ret, frame = cap.read()

    cv2image   = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)

    img   = Image.fromarray(cv2image).resize((760, 400))
    imgtk = ImageTk.PhotoImage(image = img)
    lmain.imgtk = imgtk
    lmain.configure(image=imgtk)
    lmain.after(10, show_frame)

closeButton = Button(mainWindow, text = "CLOSE", font = fontButtons, bg = white, width = 20, height= 1)
closeButton.configure(command= lambda: mainWindow.destroy())
closeButton.place(x=270,y=430)

show_frame()  #Display
mainWindow.mainloop()  #Starts GUI

预期的 GUI 在此处输入图像描述

标签: pythonopencvtkinter

解决方案


到目前为止,您的代码只能捕获视频(''ret, frame = cap.read()'')并通过 GUI 显示它(由 Tkinter 构建)。

您的下一步将是: - 在屏幕上画一条线(使用带有一组 x,y 坐标的 cv2.line 函数)。

- 处理图像以删除不需要的信息,然后检测图像上的形状/轮廓以分割矩形巧克力。

- 要检测质心,如果您知道矩形尺寸,您可以尝试 cv2.moments 或手动计算。

- 当他们通过线时计算对象,我只需使用带有对象的 x/y 像素位置的 if 语句:

假设您的传送带将物体从右向左移动

if object_position_x < detected_line_position:
    counter = counter+1
    print (counter)
else:
   print (counter)

如果您只是想绘制垂直线,请使用此代码

import cv2

def viewImage(image):
    cv2.namedWindow('Display', cv2.WINDOW_NORMAL)
    cv2.imshow('Display', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


image = cv2.imread('myimage.JPG')

#the 2 lines below are using the image.shape attributes to automatically calculate the dimension of the image
#basically it says : startpoint = middle column of the image, line 0
#                    endpoint = middle column of the image, last row
start_point = ((int(image.shape[1]/2)), 0) 
end_point = ( (int(image.shape[1]/2)), (int(image.shape[0])) )
color = (0, 0, 255)
thickness = 2

cv2.line(image, start_point, end_point, color, thickness)
viewImage(image)

希望能帮助到你


推荐阅读