Exemple #1
0
def define_roi_still(image_input, folder_path):
    roi_num = roi_input()
    image = np.array(image_input, copy=True)
    # rr = np.arange(4 * roi_num).reshape(roi_num, 4)
    scalingF = 1
    dict_file = {"cam_ID": "na"}
    height, width = image.shape
    if roi_num == 0:
        dict_file["roi_0"] = tuple([0, 0, width, height])
    else:
        for roi in range(roi_num):
            frameRS = cv2.resize(
                image, (int(width / scalingF), int(height / scalingF)))
            rr = cv2.selectROI(("Select ROI" + str(roi)), frameRS)
            # output: (x,y,w,h)
            dict_file["roi_" + str(roi)] = tuple(i * scalingF for i in rr)
            # add in ROIs
            start_point = (rr[0], rr[1])
            end_point = (rr[0] + rr[2], rr[1] + rr[3])
            cv2.rectangle(image, start_point, end_point, 220, 2)
            cv2.destroyAllWindows()
        print(dict_file)

    with open(os.path.join(folder_path, "roi_file.yaml"), "w") as file:
        documents = yaml.dump(dict_file, file)

    print("File has now been saved in specified folder as roi_file.yaml")
 def select_roi(self):
     """
     Select ROI, close window after press 'Enter'.
     self.bbox stores the ROI.
     """
     select_roi_window_name = "SelectROI, User Mouse To Drag, Press Enter to Analyze"
     cv2.namedWindow(select_roi_window_name, cv2.WINDOW_NORMAL)
     self.bbox = cv2.selectROI(select_roi_window_name, self.frame, False)
     cv2.destroyAllWindows()
def initial_manuel(frame):
    initBB = []
    while True:
        initBB.append(
            cv2.selectROI("Frame", frame, fromCenter=False,
                          showCrosshair=True))
        cv2.rectangle(
            frame, (initBB[-1][0], initBB[-1][1]),
            (initBB[-1][0] + initBB[-1][2], initBB[-1][1] + initBB[-1][3]),
            (0, 255, 0), 2)
        initBB[-1] = xywh2cxywh(initBB[-1])
        key = cv2.waitKey(0) & 0xFF
        if key == ord("n"):
            initBB[-1] = np.append(initBB[-1], 0)
        elif key == ord("q"):
            initBB = initBB[:-1]
            break
        else:
            initBB[-1] = np.append(initBB[-1], 1)
    return initBB
                hue.append(h)
                sat.append(s)
                val.append(v)

        hMaxValue = max(hue, key=hue.count)
        sMaxValue = max(sat, key=sat.count)
        vMaxValue = max(val, key=val.count)

        upperBound = (hMaxValue + RANGE, sMaxValue + RANGE, vMaxValue + RANGE)
        lowerBound = (hMaxValue - RANGE, sMaxValue - RANGE, vMaxValue - RANGE)

        print(lowerBound, "  ", upperBound)

        frame = cv2.rectangle(frame, initialBoundingBox, (255, 0, 0), 2)

    cv2.imshow("Frame", frame)

    key = cv2.waitKey(1) & 0xFF

    if key == ord("s"):
        initialBoundingBox = cv2.selectROI("Frame",
                                           frame,
                                           fromCenter=False,
                                           showCrosshair=True)
        tracker.init(frame, initialBoundingBox)
    elif key == 27:
        break

vs.stop()
cv2.destroyAllWindows()
Exemple #5
0
cap = cv2.VideoCapture(video_source)

# MOSSE: mais rápido, menos preciso
#tracker = cv2.TrackerMOSSE_create()

# CSRT: mais lento, maior precisão
# tracker = cv2.TrackerCSRT_create()

# KCF: mais rápido que CSRT, mais preciso que MOSSE
tracker = cv2.TrackerKCF_create()

# Lê o primeiro quadro
success, img = cap.read()

# Cria uma caixa limitante com o input do mouse
bounding_box = cv2.selectROI("Tracking", img, False)

# Inicia um Rastreador
tracker.init(img, bounding_box)


# Função para desenhar a caixa limitante
def drawBox(img, bounding_box):
    x, y, w, h = (int(i) for i in bounding_box)

    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)


while True:
    # Lê o frame
    success, img = cap.read()
def Varredura():
    #realiza a varredura e chama a função de analise de contornos
    img = Camera()
    #caso queira desabilitar a camera, é so comentar a linha de cima e usar as de baixo
    #img = cv2.imread("<endereço da imagem>")
    #img = cv2.resize(img, (639,479), interpolation = cv2.INTER_AREA)
    #chama a função de enquadramento
    img = Enquadramento(img)

    #a função da janela declarada é impedir q a imagem apareça gigantesca e ñ perca qualidade
    cv2.namedWindow('Deseja Recortar a imagem?', cv2.WINDOW_NORMAL)
    cv2.resizeWindow('Deseja Recortar a imagem?', (int(479 * proporcao), 479))

    ##### rotacionar 180º para melhor compreenção
    altura, largura = img.shape[:2]
    ponto = (largura / 2, altura / 2
             )  #ponto no centro da figura, ponto de giro
    rotacao = cv2.getRotationMatrix2D(ponto, 180, 1.0)
    img = cv2.warpAffine(img, rotacao, (largura, altura))

    ###primeira janela pra corte
    print("\n\n\n")
    print("--Deseja recortar a imagem?--")
    print(
        "-Sim:\n  Selecione clicando e arrastando.\n  Confirma com a tecla Enter"
    )
    print("-Não:\n  Aperte a tecla Esc\n\n\n")
    xs, ys, w, h = cv2.selectROI(
        'Deseja Recortar a imagem?',
        img)  #permite o usuario cortar a imagem com o mouse
    cv2.destroyAllWindows()
    crop_img_true = crop_img_contour = img[ys:ys + h, xs:xs +
                                           w]  #salvandoos dados do corte
    cortada = True
    if crop_img_true.shape[0] < 1:
        cortada = False
        crop_img_true = crop_img_contour = img
    print("\n\n\n")
    print(
        "--Utilize as barras para evidenciar, da melhor forma possível, os objetos desejados--"
    )
    print(
        "--O filtro dinâmico possui limitações, logo, talvez não seja possível evidenciar todos os objetos desejados de um só vez--"
    )
    #filtro dinamico
    desejo = "b"
    while 1:
        x, y, z, a, b, c = (
            tr.tracker(crop_img_true)
        )  #biblioteca que gera filtro de cores de modo iterativo

        crop_img_true = cv2.cvtColor(
            crop_img_true, cv2.COLOR_BGR2HSV
        )  #é necessario converter para hsv para passar o filtro

        #criando imagem base pra varredura com o contorno do filtro de cores
        mask_inRange = cv2.inRange(crop_img_true, (x, y, z), (a, b, c))

        #lógica para sobreposição de filtros, necessário caso o usuário queira evidencia cores distantes no espectro HSVe com intervalos
        if desejo == "a":
            mask_inRange = cv2.resize(mask_inRange,
                                      (int(479 * proporcao), 479),
                                      interpolation=cv2.INTER_AREA)
            mask_inRange_temp = cv2.resize(mask_inRange_temp,
                                           (int(479 * proporcao), 479),
                                           interpolation=cv2.INTER_AREA)

            for y in range(0, mask_inRange.shape[0]):  #percorre linhas
                for x in range(0, mask_inRange.shape[1]):  #percorre colunas
                    #mask eh uma imagem composta apenas de 0 e 255
                    if (mask_inRange_temp[y][x] == (255)):
                        mask_inRange[y][x] = (255)
            mask_inRange = cv2.resize(mask_inRange,
                                      (int(2500 * proporcao), 2500),
                                      interpolation=cv2.INTER_AREA)

        print("--Deseja avidenciar mais objetos?--")
        print(" a - Sim \n b - Não")
        desejo = input()
        if desejo == "a":
            mask_inRange_temp = mask_inRange
            crop_img_true = cv2.cvtColor(crop_img_true, cv2.COLOR_HSV2BGR)
        #caso o usuário envio qualquer coisa diferente de a, será considerado b
        else:
            break

    #caso o usuário opte por recoertar a imagem, é necessario corrigir as medidas
    if cortada == True:

        blank_space_black = np.zeros((img.shape[0], img.shape[1]), np.uint8)
        blank_space_black[:] = (0)
        blank_space_black[ys:ys + h, xs:xs + w] = mask_inRange
        mask_inRange = blank_space_black
        crop_img_true = crop_img_contour = img

    #etapa importante para que a função findContours funcione sem problemas
    _, threshold = cv2.threshold(mask_inRange, 250, 255, cv2.THRESH_BINARY)

    #varredura de contornos
    contours = []
    contours, _ = cv2.findContours(threshold, cv2.RETR_TREE,
                                   cv2.CHAIN_APPROX_NONE)

    #listas de bordas
    contornos_reais = []
    total_objetos = 0
    # tirando objetos menores que o minimo... retira ruido
    for cnt in contours:
        if cv2.contourArea(cnt) >= maxi:
            contornos_reais.append(cnt)
            total_objetos += 1

    print("\n\n")
    print("-- Total de objetos encontrados", total_objetos, " --")
    # todos os dados são obtidos atraves da mascara, uma imagem praticamente binária.
    #as edições (contornos, escrever o ID no centro do objeto) são feitas em cima da imagem crop_img_contour que é a mesma imagem justificada, enquadrada lá do inicio
    #desenhar contornos
    cv2.drawContours(crop_img_contour, contornos_reais, -1, (0, 255, 0), 5)

    crop_img_contour, tabela = Identificar_objeto(
        contornos_reais, crop_img_contour,
        img)  #chamar a função Identificar_objetos
    img_final = cv2.resize(crop_img_contour, (850, 512),
                           interpolation=cv2.INTER_AREA)
    cv2.imwrite("img_final.jpg",
                img_final)  #salvando a imagem na pasta do programa

    ###tabela
    tabela_df = pd.DataFrame(data=tabela,
                             columns=[
                                 'Id',
                                 'Centro_X',
                                 'Centro_Y',
                                 'Ângulo',
                             ])
    tabela_df.to_csv("tabela.csv")

    return tabela_df, img_final
    "Largura mínima para validar uma caixa limitante como pertencente a um carro",
    default=80)
args = parser.parse_args()


def get_center(x, y, w, h):
    return x + int(w / 2), y + int(h / 2)


cap = cv2.VideoCapture(args.video_source)

# Lê o primeiro quadro
success, img = cap.read()

# Cria uma caixa limitante com o input do mouse
bounding_box = cv2.selectROI("Classica", img, False)
cx, cy, cw, ch = (bounding_box[i] for i in range(4))

subtraction = cv2.bgsegm.createBackgroundSubtractorMOG()
vehicle_counter = 0

result = cv2.VideoWriter('result.avi', cv2.VideoWriter_fourcc(*'XVID'), 30.0,
                         (1280, 720))

while True:
    # Lê um frame
    success, img = cap.read()

    if success:
        # Desenha um retângulo branco na região de interesse
        cv2.rectangle(img, (cx, cy), (cx + cw, cy + ch), (255, 255, 255), 2)
Exemple #8
0
from cv2 import cv2
import numpy as np

cap = cv2.VideoCapture(0)

tracker = cv2.TrackerCSRT_create()

for i in range(10):
    s, frame = cap.read()

bbox = cv2.selectROI("Video", frame, True)
tracker.init(frame, bbox)


def spiral_cw(A):
    out = []
    while (A.size):
        out.append(A[0])  # take first row
        A = A[1:].T[::-1]  # cut off first row and rotate counterclockwise
    return np.concatenate(out)


while True:
    s, frame = cap.read()
    success, bbox = tracker.update(frame)
    if success:
        x, y, w, h = bbox
        x, y, w, h = int(x), int(y), int(w), int(h)
        frame[y:y + h, x:x + w] = spiral_cw(frame[y:y + h, x:x + w])
        # cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,150), 2)
if not success:
  print('Failed to read video')
  sys.exit(1)


## Select boxes
bboxes = []
colors = [] 
 
# OpenCV's selectROI function doesn't work for selecting multiple objects in Python
# So we will call this function in a loop till we are done selecting all objects
while True:
  # draw bounding boxes over objects
  # selectROI's default behaviour is to draw box starting from the center
  # when fromCenter is set to false, you can draw box starting from top left corner
  bbox = cv2.selectROI('MultiTracker', frame)
  bboxes.append(bbox)
  colors.append((randint(0, 255), randint(0, 255), randint(0, 255)))
  print("Press q to quit selecting boxes and start tracking")
  print("Press any other key to select next object")
  k = cv2.waitKey(0) & 0xFF
  if (k == 113):  # q is pressed
    break
 
print('Selected bounding boxes {}'.format(bboxes))


# Specify the tracker type
trackerType = "CSRT"   
 
# Create MultiTracker object
                          (0, 255, 0), 2, 1)
        else:  # 추적 실패
            cv2.putText(img_draw, "Tracking fail.", (100, 80),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2,
                        cv2.LINE_AA)
    trackerName = tracker.__class__.__name__
    cv2.putText(img_draw,
                str(trackerIdx) + ":" + trackerName, (100, 20),
                cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2, cv2.LINE_AA)

    cv2.imshow(win_name, img_draw)
    key = cv2.waitKey(delay) & 0xff
    # 스페이스 바 또는 비디오 파일 최초 실행 ---④
    if key == ord(' ') or (video_src != 0 and isFirst):
        isFirst = False
        roi = cv2.selectROI(win_name, frame, False)  # 초기 객체 위치 설정
        print(roi)
        if roi[2] and roi[3]:  # 위치 설정 값 있는 경우
            tracker = trackers[trackerIdx]()  # 트랙커 객체 생성 ---⑤
            isInit = tracker.init(frame, roi)
    elif key in range(48, 56):  # 0~7 숫자 입력   ---⑥
        trackerIdx = key - 48  # 선택한 숫자로 트랙커 인덱스 수정
        if bbox is not None:
            tracker = trackers[trackerIdx]()  # 선택한 숫자의 트랙커 객체 생성 ---⑦
            isInit = tracker.init(frame, bbox)  # 이전 추적 위치로 추적 위치 초기화
    elif key == 27:
        break
else:
    print("Could not open video")
cap.release()
cv2.destroyAllWindows()
Exemple #11
0
        print("Could not open video")
        sys.exit()

    # Read first frame.
    video.set(1, 600)
    ok, frame = video.read()
    # video.set(1, 0)
    if not ok:
        print('Cannot read video file')
        sys.exit()

    # Define an initial bounding box
    bbox = (287, 23, 86, 320)

    # Uncomment the line below to select a different bounding box
    bbox = cv2.selectROI(frame, False)

    # Initialize tracker with first frame and bounding box
    ok = tracker.init(frame, bbox)

    while True:
        # Read a new frame
        ok, frame = video.read()
        if not ok:
            break

        # Start timer
        timer = cv2.getTickCount()

        # Update tracker
        ok, bbox = tracker.update(frame)
Exemple #12
0
    #
    #frame = cv2.resize(frame, (1366,768))

    fgmask = fgbg.apply(frame)

    fgmask = cv2.erode(fgmask, kernel, iterations=1)
    fgmask = cv2.medianBlur(fgmask, 3)
    fgmask = cv2.dilate(fgmask, kernel, iterations=2)

    fgmask = (fgmask > 200).astype(np.uint8) * 255
    colorMask = cv2.bitwise_and(frame, frame, mask=fgmask)

    if (crop):
        fromCenter = False
        img = colorMask
        r = cv2.selectROI(img, fromCenter)
        imCrop = img[int(r[1]):int(r[1] + r[3]), int(r[0]):int(r[0] + r[2])]
        crop = False
        camshift = True
        imCropMask = cv2.cvtColor(imCrop, cv2.COLOR_BGR2GRAY)
        ret, imCropMask = cv2.threshold(imCropMask, 30, 255, cv2.THRESH_BINARY)
        his = smooth(1, rgbh([imCrop], imCropMask))

        roiBox = (int(r[0]), int(r[1]), int(r[2]), int(r[3]))
        cv2.destroyWindow("ROI selector")

    if (camshift):

        cv2.putText(frame, "Center roiBox", (0, 10), font, 0.5, (0, 255, 0), 2,
                    cv2.LINE_AA)
        cv2.putText(frame, "Estimated Pos", (0, 30), font, 0.5, (255, 255, 0),