Motion detected problem python

I made an application with Tkinder using the OpenCV library on MP4 recordings from a security camera. The video sometimes progresses very slowly when the frame rate is high, and sometimes it doesn’t detect any moving parts at all. However, there is no problem with short videos. It works as I want. It’s more stable, and although it has graphics card support, I can’t use it with high performance. Can you help me?

Hi @Selcuk_Kartal,

I think the issue comes from a combination of video decoding speed and how the frames are being processed in your Tkinter loop.

A few points you can check:

  1. VideoCapture and frame reading

    • By default, cv2.VideoCapture reads frames sequentially from the CPU.
    • High-frame-rate or long MP4 files may cause lag because decoding + Tkinter update both run on the main thread.
    • Try using a separate thread or a buffer queue to read frames continuously, while your main loop just displays the latest frame.
  2. Frame skipping

    • If real-time display is more important than processing every frame, you can skip frames intentionally when the queue gets too large:

      ret, frame = cap.read()
      if not ret:
          break
      # Optionally resize frame to reduce processing load
      frame = cv2.resize(frame, (640, 360))
      
  3. GPU / CUDA acceleration

    • Standard cv2.VideoCapture does not automatically use your GPU.

    • If you built OpenCV with CUDA or OpenCV-FFmpeg support, you can try:

      cap = cv2.cudacodec.createVideoReader("video.mp4")
      

      This lets decoding happen on the GPU, which can be much faster for long or high-fps videos.

    • Alternatively, if you only need motion detection, you can upload frames to GPU with cv2.cuda_GpuMat() and run operations there.

  4. Motion detection stability

    • For long videos, lighting changes and background drift may confuse simple subtraction methods.

    • Try background subtraction algorithms in OpenCV:

      backSub = cv2.createBackgroundSubtractorMOG2()
      mask = backSub.apply(frame)
      

      These are more robust for moving object detection over long recordings.


Summary:

  • Use a separate thread to read frames continuously.
  • Consider resizing or skipping frames to keep Tkinter responsive.
  • If you want GPU acceleration, build OpenCV with CUDA and use cv2.cudacodec.
  • For motion detection, try background subtraction methods instead of only frame differencing.

Hope this helps! If you can share a small code snippet of your Tkinter loop, I can give more specific suggestions.

1 Like

“”"

Motion Detector - Başlatıcı

============================

Hangi modu kullanmak istediğinizi seçin:

1. Tek Video Modu

2. Toplu Video Modu

“”"

import tkinter as tk

from tkinter import ttk, messagebox

import subprocess

import sys

from pathlib import Path

class LauncherGUI:

"""Başlatıcı GUI"""



def \__init_\_(self, root):

    self.root = root

    self.root.title("Motion Detector - Başlatıcı")

    self.root.geometry("500x400")

    self.root.resizable(False, False)



    self.create_widgets()



def create_widgets(self):

    """GUI elemanları"""



    \# Başlık

    title_frame = ttk.Frame(self.root, padding=30)

    title_frame.pack(fill='x')



    ttk.Label(

        title_frame,

        text="🎥 Motion Detector",

        font=('Arial', 20, 'bold'),

        foreground='#2c3e50'

    ).pack()



    ttk.Label(

        title_frame,

        text="Hangi modu kullanmak istersiniz?",

        font=('Arial', 11),

        foreground='#555'

    ).pack(pady=10)



    \# Seçenekler

    options_frame = ttk.Frame(self.root, padding=20)

    options_frame.pack(fill='both', expand=True)



    \# Tek Video

    single_frame = ttk.LabelFrame(options_frame, text="📹 Tek Video Modu", padding=20)

    single_frame.pack(fill='x', pady=10)



    ttk.Label(

        single_frame,

        text="• Bir video dosyasını analiz edin\\n"

             "• ROI (alan) seçimi yapın\\n"

             "• Detaylı analiz ve rapor",

        justify='left'

    ).pack(anchor='w')



    ttk.Button(

        single_frame,

        text="Tek Video Modunu Başlat",

        command=self.launch_single,

        width=30

    ).pack(pady=(10, 0))



    \# Toplu Video

    batch_frame = ttk.LabelFrame(options_frame, text="📚 Toplu Video Modu", padding=20)

    batch_frame.pack(fill='x', pady=10)



    ttk.Label(

        batch_frame,

        text="• Birden fazla video işleyin\\n"

             "• Klasör seçimi desteği\\n"

             "• Toplu rapor ve kayıt",

        justify='left'

    ).pack(anchor='w')



    ttk.Button(

        batch_frame,

        text="Toplu Video Modunu Başlat",

        command=self.launch_batch,

        width=30

    ).pack(pady=(10, 0))



    \# Alt bilgi

    footer_frame = ttk.Frame(self.root, padding=10)

    footer_frame.pack(side='bottom', fill='x')



    ttk.Label(

        footer_frame,

        text="Motion Detector v1.0 - Video Analiz Aracı",

        font=('Arial', 8),

        foreground='#999'

    ).pack()



def launch_single(self):

    """Tek video modunu başlat"""

    try:

        \# Dosya yolunu al

        current_dir = Path(\__file_\_).parent

        gui_path = current_dir / "gui.py"



        self.root.destroy()

        subprocess.run(\[sys.executable, str(gui_path)\])

    except Exception as e:

        messagebox.showerror("Hata", f"Başlatma hatası: {str(e)}")



def launch_batch(self):

    """Toplu video modunu başlat"""

    try:

        \# Dosya yolunu al

        current_dir = Path(\__file_\_).parent

        batch_gui_path = current_dir / "batch_gui.py"



        self.root.destroy()

        subprocess.run(\[sys.executable, str(batch_gui_path)\])

    except Exception as e:

        messagebox.showerror("Hata", f"Başlatma hatası: {str(e)}")

def main():

"""Ana fonksiyon"""

root = tk.Tk()

app = LauncherGUI(root)

root.mainloop()

if _name_ == “_main_”:

main()

No AI-generated posts please. It’s a waste of everyone’s time to debunk these posts, and anyone who wants AI output can get it for free, so there is no justification for posting any of that here. Do not post AI-generated content.

Please edit the post and use proper formatting for pieces of code. As is, your post is hard to read, and littered with issues that come from whatever you did when you copy-pasted the code. In its current state, it cannot be taken and executed.

Also, that code doesn’t even use OpenCV, so why post it?

yardımcı olabilir misiniz?

Why do you think its AI generated?? I know it looks like AI generated but its wrote by me manually I used AI for some small part of research but I wrote this with proper sequence.