Erro ao executar o “bg mask”

Home Fóruns Fórum Detecção de Movimentos com Python e OpenCV Erro ao executar o “bg mask”

Visualizando 10 posts - 1 até 10 (de 10 do total)
  • Autor
    Posts
  • #33141
    Luiz Felipe
    Participante

    def main():
    while cap.isOpened():
    ok, frame = cap.read()
    #print(‘frame.shape’)

    frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5)
    #print(frame.shape)

    bg_mask = bg_subtractor.apply(frame)
    fg_mask = getFiltrer(bg_mask, ‘dilation’)

    if not ok:
    print(‘Erro’)
    break

    cv2.imshow(‘Frame’, frame)
    cv2.imshow(‘BG mask’, bg_mask)
    cv2.imshow(‘BG mask filtrer ‘, fg_mask)

    if cv2.waitKey(1) & 0xFF == ord(‘q’):
    break
    main()

    esse é o codigo, porém da esse erro

     

    Traceback (most recent call last):
    File “C:\Users\luizf\pythonProject5\outros_algoritmos.py”, line 84, in <module>
    main()
    File “C:\Users\luizf\pythonProject5\outros_algoritmos.py”, line 80, in main
    cv2.imshow(‘BG mask filtrer ‘, fg_mask)
    cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’

    #33146
    Dalton Vargas
    Moderador

    Olá Luiz!

    Normalmente o erro -215:Assertion failed ocorre quando não foi possível carregar a imagem/vídeo de entrada.

    Poderia compartilhar o código completo? Preciso revisar todas as funções, o carregamento do vídeo, importação das bibliotecas… Este que você mandou tem só as chamadas.

    #33149
    Luiz Felipe
    Participante

    import numpy as np
    import cv2
    import sys
    from random import randint

    TEXT_COLOR = (randint(0, 255), randint(0,255), randint (0,255))
    BORDER_COLOR = (randint(0, 255), randint(0,255), randint (0,255))
    FONT = cv2.FONT_HERSHEY_SIMPLEX
    VIDEO_SOURCE =”Video/Traffic_4.mp4″

    #print (TEXT_COLOR)

    BGS_TYPES = (‘GMG’, ‘MOG’, ‘MOG2’, ‘KNN’, ‘CNT’)

    #print(BGS_TYPES[1])

    def getKernel(KERNEL_TYPE):
    if KERNEL_TYPE == ‘dilation’:
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
    if KERNEL_TYPE == ‘opening’:
    kernel = np.ones((3,3), np.uint8)
    if KERNEL_TYPE == ‘closing’:
    kernel = np.ones((3,3), np.uint8)

    return kernel
    #print(getKernel(‘opening’))

    def getFiltrer(img, filter):
    if filter == ‘closing’:
    return cv2.morphologyEx(img, cv2.MORPH_CLOSE, getKernel(‘closing’), iterations=2)
    if filter == ‘opening:’:
    return cv2.morphologyEx(img, cv2.MORPH_OPEN, getKernel(‘opening’), iterations=2)
    if filter == ‘dilation:’:
    return cv2.dilate(img, getKernel(‘dilation’), iterations=2)
    if filter == ‘combine’:
    closing = cv2.morphologyEx(img, cv2.MORPHCLOSE, getKernel(‘closing’), iterations=2)
    opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, getKernel(‘opening’), iterations=2)
    dilation = cv2.dilate(opening, getKernel(‘dilation’), iterations=2)
    return dilation

    def getBGSubtractor(BGS_TYPE):
    if BGS_TYPE == ‘GMG’:
    return cv2.bgsegm.createBackgroundSubtractorGMG(initializationFrames = 120, decisionThreshold=0.8)

    if BGS_TYPE == ‘MOG’:
    return cv2.bgsegm.createBackgroundSubtractorMOG(history=200, nmixtures=5,
    backgroundRatio=0.7, noiseSigma=0)
    if BGS_TYPE == ‘MOG2’:
    return cv2.createBackgroundSubtractorMOG2(history=500, detectShadows=True, varThreshold=100)

    if BGS_TYPE == ‘KNN’:
    return cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)

    if BGS_TYPE == ‘CNT’:
    return cv2.createBackgroundSubtractorCNT(minPixelStability=15, useHistory=True, maxPixelStability=15*60, isParallel=True)

    print(‘Detector Inválido’)
    sys.exit(1)

    cap = cv2.VideoCapture(VIDEO_SOURCE)
    bg_subtractor = getBGSubtractor(BGS_TYPES[0])

    def main():
    while cap.isOpened():
    ok, frame = cap.read()
    #print(‘frame.shape’)

    frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5)
    #print(frame.shape)

    bg_mask = bg_subtractor.apply(frame)
    fg_mask = getFiltrer(bg_mask, ‘dilation’)

    if not ok:
    print(‘Erro’)
    break

    cv2.imshow(‘Frame’, frame)
    cv2.imshow(‘BG mask’, bg_mask)
    cv2.imshow(‘BG mask filtrer ‘, fg_mask)

    if cv2.waitKey(1) & 0xFF == ord(‘q’):
    break
    main()

    #33154
    Dalton Vargas
    Moderador

    Oi Luiz!

    Estou analisando o código, assim que eu terminar mando aqui pra você.

    #33156
    Luiz Felipe
    Participante

    certo

    #33157
    Dalton Vargas
    Moderador

    Luiz,

    Fiz as correções no seu fonte e testei com todos os BGS, a princípio está tudo funcionando. Segue abaixo:

     

    #33161
    Dalton Vargas
    Moderador
    import numpy as np
    import cv2
    import sys
    from random import randint
    
    TEXT_COLOR = (randint(0, 255), randint(0,255), randint (0,255))
    BORDER_COLOR = (randint(0, 255), randint(0,255), randint (0,255))
    FONT = cv2.FONT_HERSHEY_SIMPLEX
    
    # //////////////
    # VIDEO_SOURCE =”Video/Traffic_4.mp4″
    # Correção:
    VIDEO_SOURCE = "videos/Traffic_4.mp4"
    
    #print (TEXT_COLOR)
    # /////////////////
    # BGS_TYPES = ('GMG', 'MOG', 'MOG2', 'KNN', 'CNT')
    # Correção:
    # Neste vetor de BGS deve ser em aspas duplas e não simples,
    # também estava entre parenteses e o correto é entre colchetes
    BGS_TYPES = ["GMG", "MOG", "MOG2", "KNN", "CNT"]
    
    #print(BGS_TYPES[1])
    
    def getKernel(KERNEL_TYPE):
        if KERNEL_TYPE == "dilation":
            kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
        if KERNEL_TYPE == "opening":
            kernel = np.ones((3, 3), np.uint8)
        if KERNEL_TYPE == "closing":
            kernel = np.ones((3, 3), np.uint8)
    
        return kernel
    #print(getKernel('opening'))
    
    def getFiltrer(img, filter):
        if filter == 'closing':
            return cv2.morphologyEx(img, cv2.MORPH_CLOSE, getKernel("closing"), iterations=2)
    
        if filter == 'opening':
            return cv2.morphologyEx(img, cv2.MORPH_OPEN, getKernel("opening"), iterations=2)
    
        if filter == 'dilation':
            return cv2.dilate(img, getKernel("dilation"), iterations=2)
    
        if filter == 'combine':
            closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, getKernel("closing"), iterations=2)
            opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, getKernel("opening"), iterations=2)
            dilation = cv2.dilate(opening, getKernel("dilation"), iterations=2)
    
            return dilation
    
    def getBGSubtractor(BGS_TYPE):
        # Correção:
        # deve ser em aspas duplas e não simples,
        # if BGS_TYPE == 'GMG':
        if BGS_TYPE == "GMG":
            return cv2.bgsegm.createBackgroundSubtractorGMG(initializationFrames = 120, decisionThreshold=0.8)
    
        # Correção:
        # deve ser em aspas duplas e não simples,
        # if BGS_TYPE == 'MOG':
        if BGS_TYPE == "MOG":
            return cv2.bgsegm.createBackgroundSubtractorMOG(history=200, nmixtures=5,
        backgroundRatio=0.7, noiseSigma=0)
    
        # Correção:
        # deve ser em aspas duplas e não simples,
        # if BGS_TYPE == 'MOG2':
        if BGS_TYPE == "MOG2":
            return cv2.createBackgroundSubtractorMOG2(history=500, detectShadows=True, varThreshold=100)
    
        # Correção:
        # deve ser em aspas duplas e não simples,
        # if BGS_TYPE == 'KNN':
        if BGS_TYPE == "KNN":
            return cv2.createBackgroundSubtractorKNN(history=500, dist2Threshold=400, detectShadows=True)
    
        # Correção:
        # deve ser em aspas duplas e não simples,
        # if BGS_TYPE == 'CNT':
        if BGS_TYPE == "CNT":
            # Correção:
            # Precisa incluir o bgsem para acessar ao BG CNT
            # return cv2.createBackgroundSubtractorCNT(minPixelStability=15, useHistory=True, maxPixelStability=15*60, isParallel=True)
            return cv2.bgsegm.createBackgroundSubtractorCNT(minPixelStability=15, useHistory=True, maxPixelStability=15*60, isParallel=True)
    
        print("Detector inválido")
        sys.exit(1)
    
    cap = cv2.VideoCapture(VIDEO_SOURCE)
    bg_subtractor = getBGSubtractor(BGS_TYPES[4])
    
    def main():
        while cap.isOpened():
            ok, frame = cap.read()
            #print('frame.shape')
            if not ok:
                print('Erro')
                break
    
            frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5)
            #print(frame.shape)
    
            bg_mask = bg_subtractor.apply(frame)
            fg_mask = getFiltrer(bg_mask, 'dilation')
    
            cv2.imshow('Frame', frame)
            cv2.imshow('BG mask', bg_mask)
            cv2.imshow('BG mask filtrer ', fg_mask)
    
            if cv2.waitKey(1) & 0xFF == ord('q'): 
                break
            
    main()
    #33492
    Luiz Felipe
    Participante

    boa noite
    ainda continua dando erro kkkk

    #33494
    Dalton Vargas
    Moderador

    Poderia compartilhar o erro?

    #33553
    Luiz Felipe
    Participante

    o mesmo erro que eu citei na 1 postagem

Visualizando 10 posts - 1 até 10 (de 10 do total)
  • Você deve fazer login para responder a este tópico.