예제 #1
0
def run(video_file, tracker_type):
    video = cv2.VideoCapture(video_file)
    if not video.isOpened():
        sys.exit()

    colors = []
    tracker = None
    fps = None
    while True:
        ok, frame = video.read()
        if not ok:
            break

        if not video_file:
            frame = cv2.flip(frame, 1, 0)

        key_code = cv2.waitKey(1)
        if key_code == ord('q'):
            break
        elif key_code == ord(' '):
            bboxs = cv2.selectROIs(WINDOW_NAME, frame, showCrosshair=False)
            if len(bboxs):
                tracker, colors = get_multi_tracker(tracker_type, frame, bboxs)
            else:
                tracker = None

        if tracker:
            tracker_update(frame, tracker, colors)

        cv2.imshow(WINDOW_NAME, frame)
예제 #2
0
def main():
    ROIs = cv2.selectROIs('Select -> <Enter> -> Select -> <Enter> -> <Esc>',
                          IMAGE,
                          fromCenter=False)  # (xmin, ymin, w, h)
    ROI_bboxes = list(map(convert_roi_to_bbox, ROIs))

    [print(f'Box {i}: {bbox}') for i, bbox in enumerate(ROI_bboxes)]
예제 #3
0
    def select_rois_over_image(cls, im, save_to, delimiter, quotechar):
        """"""
        print("------------------------------------------------------------")
        print("If there are no ROIs being selected,")
        print("Pressing ESC will create 1 ROI with the size of whole image.")
        print("------------------------------------------------------------")
        rois = cv.selectROIs("Select ROIs", im)
        if len(rois) == 0:
            h, w, __ = im.shape
            rois = [[0, 0, w, h]]

        with open(save_to, "w+", newline="") as csvfile:
            writer = csv.DictWriter(
                csvfile,
                fieldnames=cls.fields.keys(),
                delimiter=delimiter,
                quotechar=quotechar,
                quoting=csv.QUOTE_NONNUMERIC,
            )
            writer.writeheader()

            print("ROIs data:")
            for roi_n, roi_val in enumerate(rois):
                x, y, w, h = roi_val
                roi = cls.create_roi([roi_n, x, y, w, h])
                cls.add_default(roi)

                writer.writerow(roi)
                print(roi)
def get_color_stats(bgr, hsv):
    """
    Allows the user to select rectangular regions in an img that represents a color class
    and returns the stats (mu, std) for the color values in hsv space
    """
    crop = np.empty((0, 3))
    for x, y, ww, hh in cv2.selectROIs("", bgr):
        _crop = hsv[y:y + hh, x:x + ww].reshape(-1, 3)
        crop = np.concatenate((crop, _crop), axis=0)
    h, s, v = crop.transpose()

    # hue values wrap around. So we take the hue vector mean
    # and convert it back to a hue value
    _h = h * math.pi * 2
    hc, hs = np.cos(_h), np.sin(_h)
    hmu = (math.atan2(hs.mean(), hc.mean()) / (math.pi * 2)) % 1

    # center hue values around the mean to get a correct std
    _h = h.copy()
    if hmu < 0.5:
        _h[_h > hmu + 0.5] -= 1
    else:
        _h[_h < hmu - 0.5] += 1
    crop = np.stack([_h, s, v], axis=-1)
    mu, std = crop.mean(axis=0), crop.std(axis=0)
    mu[0] = hmu
    return mu, std
예제 #5
0
 def OnBtnSelectAreaClicked(self):
     rgb_frame = self._current_frame
     cv2.cvtColor(rgb_frame, cv2.COLOR_RGB2BGR, rgb_frame)
     self._areas = cv2.selectROIs('Select Area', self._current_frame, False)
     cv2.destroyWindow('Select Area')
     frame = cvrect.draw_rects(self._current_frame, self._areas,
                               (0, 0, 255))
     frame = cvrect.draw_lines(frame, self._lines, (0, 0, 255))
     self.SetTrackingFrame(frame)
예제 #6
0
def draw_boxes(images):
    all_rois = []
    for im in images:
        rois = {}
        for roi_type in ['text', 'checkbox', 'signature']:
            print(roi_type)
            rois[roi_type] = cv2.selectROIs("Image", im, False, False)
        all_rois.append(rois)
    return all_rois
예제 #7
0
def Select_Regions(frame):
	ROA = np.array([])
	ROIs = np.array([])
	cv2.namedWindow('real image')
	cv2.setMouseCallback('real image', draw, 0)
	if path_roa:
	    key = input("Saved ROA detected. Press Enter if you want to proceed with it otherwise press anything and Enter")
	    if key == '':
	        #read from csv write into ROA
	        ROA = genfromtxt('ROA.csv', delimiter=',')
	        frame = frame[int(ROA[1]):int(ROA[1]+ROA[3]), int(ROA[0]):int(ROA[0]+ROA[2])]    
	        
	    else:
	        ROA_det = cv2.selectROI('Select Region of Area', frame, False)	      
	        ROA = np.array(ROA_det)
	        ROA = np.asarray(ROA)
	        np.savetxt("ROA.csv", ROA, delimiter=",")
	        cv2.destroyWindow('Select Region of Area')
	        frame = frame[int(ROA_det[1]):int(ROA_det[1]+ROA_det[3]), int(ROA_det[0]):int(ROA_det[0]+ROA_det[2])]    

	else:
	    ROA_det = cv2.selectROI('Select Region of Area', frame, False)	      
	    ROA = np.array(ROA_det)
	    ROA = np.asarray(ROA)
	    np.savetxt("ROA.csv", ROA, delimiter=",")
	    cv2.destroyWindow('Select Region of Area')
	    frame = frame[int(ROA_det[1]):int(ROA_det[1]+ROA_det[3]), int(ROA_det[0]):int(ROA_det[0]+ROA_det[2])]    

	
	if path_rois:
	    key = input("Saved ROIs detected. Press Enter if you want to proceed with it otherwise press anything and Enter")
	    if key == '':
	        #read from csv write into ROIs
	        ROIs = genfromtxt('ROIs.csv', delimiter=',')
	    else:
	       cv2.imshow('real image', frame)
	       if cv2.waitKey(20) & 0xFF == ord('q'):
	           print(ix)
	           print(iy)
	       #print(boxes)
	    while  True:
	        	a = 2
	    '''
	        ROIs = cv2.selectROIs('Select Region of interests', frame, False)	      
	        ROIs = np.array(ROIs)
	        ROIs = np.asarray(ROIs)
	        np.savetxt("ROIs.csv", ROIs, delimiter=",")
	        cv2.destroyWindow('Select Region of interests')
	        '''
	else:
	    ROIs = cv2.selectROIs('Select Region of interests', frame, False)	      
	    ROIs = np.array(ROIs)
	    ROIsA = np.asarray(ROIs)
	    np.savetxt("ROIs.csv", ROIs, delimiter=",")
	    cv2.destroyWindow('Select Region of interests')
	
	return ROA , ROIs
def select_multiple_roi(img):
    """
    DOES NOT WORK

    """
    regions = cv2.selectROIs("Select regions", img, False, False)
    for r in regions:
        cv2.rectangle(img, (r[0], r[1]), (r[2] + r[0], r[3] + r[1]),
                      (255, 0, 0), 2)
    cv2.imshow("image", img)
    cv2.waitKey(0)
예제 #9
0
def init_rects_from_raid(name):
    raid_screenshot = get_screen()
    from_center = False
    show_crosshair = False
    rects = cv2.selectROIs(name,
                           raid_screenshot,
                           fromCenter=from_center,
                           showCrosshair=show_crosshair)
    points = [Point(rect[0], rect[1], rect[2], rect[3]) for rect in rects]
    cv2.destroyAllWindows()
    return points
예제 #10
0
def multi_rois(im):
    # Select multiple ROI
    roi = cv2.selectROIs("Image", im, 0, 0)

    for i in range(len(roi)):
        # Crop image
        im_crop = im[int(roi[i][1]):int(roi[i][1] + roi[i][3]),
                     int(roi[i][0]):int(roi[i][0] + roi[i][2])]

        # Show the image
        cv2.imshow("Cropped Image: " + str(i), im_crop)
예제 #11
0
def roi_select(array,
               toast_title,
               winName="ERROR YOU HAVEN'T NAMED THIS WINDOW!!"):
    rois = cv2.selectROIs(winName,
                          array,
                          showCrosshair=False,
                          fromCenter=False)
    cv2.destroyAllWindows()
    toaster.show_toast(toast_title,
                       "Captured %s ROI's" % (len(rois)),
                       duration=2)
    return rois
예제 #12
0
def GetROI(img):
    imgCounter = img.copy()
    cv2.putText(imgCounter,
                'Please select a part of a counter and press Enter', (1, 20),
                cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2,
                cv2.LINE_AA)
    cv2.putText(imgCounter, 'Press Esc when you finished', (1, 40),
                cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2,
                cv2.LINE_AA)
    counter = cv2.selectROIs('Counter', imgCounter, False)
    cv2.destroyAllWindows()
    return counter
예제 #13
0
 def cortarImagen(self):
     self.comboNuevasRegiones.clear()
     self.recorteLabel.hide()
     self.continuarbtn.hide()
     self.puntos = []
     listaPuntos = []
     ROIs = []
     self.aux = self.imagen.copy()
     cv2.namedWindow("Imagen", cv2.WINDOW_NORMAL)
     cv2.resizeWindow("Imagen", self.anchoImg, self.alturaImg)
     ROIs = cv2.selectROIs("Imagen", self.aux)
     cv2.destroyWindow("Imagen")
     for rect in ROIs:  #Añade todos los recortes a la variable puntos
         x1 = int(rect[0])
         y1 = int(rect[1])
         x2 = int(rect[2])
         y2 = int(rect[3])
         listaPuntos = [[x1, y1], [(x2 + x1), y1], [x1, (y1 + y2)],
                        [(x1 + x2), (y1 + y2)]]
         self.puntos.append(listaPuntos)
     #
     for i in range(len(ROIs)):
         self.comboNuevasRegiones.addItem("Region " + str(i + 1))
     if len(self.puntos) >= 1:
         self.dst = recortarImagen(self.aux, self.puntos[0])
         self.cortarImagenbtn.show()
         self.guardarbtn.show()
         self.comboNuevasRegiones.show()
         self.labelRegionMsg.show()
         self.imagenPixMap = formatoPixMap(self.dst)
         imgW = round(37 / 100 * self.anchowin)
         imgH = round(68 / 100 * self.alturawin)
         self.imagenPixMap = self.imagenPixMap.scaled(imgW, imgH)
         self.recorteLabel.setPixmap(self.imagenPixMap)
         self.recorteLabel.show()
         self.move(50, 50)
         self.textLabel.hide()
     else:
         self.cortarImagenbtn.hide()
         self.guardarbtn.hide()
         self.comboNuevasRegiones.hide()
         self.labelRegionMsg.hide()
         self.textLabel.show()
         self.continuarbtn.show()
         msg = QMessageBox()
         msg.setText(
             "Las regiones no se guardaron correctamente, porfavor seguir las instrucciones mostradas en pantalla"
         )
         msg.setWindowTitle("Error")
         msg.exec_()
예제 #14
0
    def configure(self, camera):
        print('Configuration starting..')
        frame = camera.getSingleFrame()

        print('Select the reference region')
        template_regions = cv2.selectROIs(
            'Select the reference region(s), enter to confirm spot, esc to close',
            frame)
        for template_region in template_regions:
            self.template_regions.append(template_region)
        cv2.destroyAllWindows()

        print('Select spots')
        regions = cv2.selectROIs(
            'Select spots, enter to confirm spot, esc to close', frame)
        spot_id = 1  # Spots start at 1
        for region in regions:
            self.parking_spots.append(
                ParkingLotSpot(spot_id, (region[0], region[1]),
                               (region[0] + region[2], region[1] + region[3]),
                               region[2] / 3))
            spot_id += 1
        cv2.destroyAllWindows()
def selectROIs(frame, xa, ya):

    print('identify nest area')
    box_n = cv2.selectROIs("Frame", frame, fromCenter=False)
    ((xn, yn, wn, hn), ) = tuple(map(tuple, box_n))
    nest_corners = {
        'xmin': xn - xa,
        'ymin': yn - ya,
        'width': wn,
        'height': hn,
    }
    cv2.destroyAllWindows()

    return nest_corners
예제 #16
0
def ROI():

    while True:
        global r
        ret, im0 = cap.read()
        im0 = imutils.resize(im0, width=900)
        showCrosshair = False
        fromCenter = False
        r = cv2.selectROIs("Image", im0, showCrosshair, fromCenter)
        if (len(r) == 0):
            cv2.putText(im0, 'Please select Region of interest', (10, 500),
                        cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
            print('Selecrt intrusion')
        else:
            break
def MouseRoI(dirpath):
    """
    openfaceのlandmarkを使って,顔領域を選択し平均化されたRGBを返す
    """
    # ファイル一覧を取得
    files = []
    i = 0
    for filename in os.listdir(dirpath):
        if os.path.isfile(os.path.join(dirpath, filename)): #ファイルのみ取得
            files.append(filename)

    # マウスイベント
    winname = 'Image'
    image = cv2.imread(os.path.join(dirpath, files[816]))
    rois = cv2.selectROIs(winname, image, False) # x,y,w,h
    cv2.destroyAllWindows()
    for r in rois:
        print("x:{}, y:{}, w:{}, h:{}".format(r[0],r[1],r[2],r[3]))
 
    
    # loop from first to last frame
    for fname in files[816:]:
        frame = cv2.imread(os.path.join(dirpath, fname))
        j = 0
        for r in rois:
            img_roi = frame[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])]
            if j == 0:
                ave_rgb_roi = AveragedRGB(img_roi)
            else:
                ave_rgb_roi = np.concatenate([ave_rgb_roi,AveragedRGB(img_roi)], axis=1)
            j = j+1
    
        if i == 0:
            rgb_components = ave_rgb_roi
        else:   
            rgb_components = np.concatenate([rgb_components, ave_rgb_roi], axis=0)

        # plot
        for r in rois:
            cv2.rectangle(frame,(r[0],r[1]),(r[2]+r[0],r[3]+r[1]), (255, 0, 0),thickness=3)
        cv2.imshow("frame", frame)
        i = i + 1
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cv2.destroyAllWindows()
    return rgb_components
def create_rois_list(window_title, crops, full_image, project_size=10):
    shrink_factor = 5
    resized = cv2.resize(full_image, (0, 0),
                         fx=1 / shrink_factor,
                         fy=1 / shrink_factor)
    rois = cv2.selectROIs(window_title, resized)
    cv2.destroyAllWindows()
    if type(rois) is not tuple:
        rois = [Rect(*roi) for roi in (rois * shrink_factor).tolist()]
        crops = [[
            crop for crop in crops
            if Rect(crop[1][1], crop[1][0], crop[0].shape[1],
                    crop[0].shape[0]).intersection(r).area() > 0
        ] for r in rois]
        return crops
    else:
        return []
예제 #19
0
def imageClickRegions(image_name, image_wh_tuple):
    img = cv.imread("image_name")
    img = cv.resize(img, dsize=image_wh_tuple, interpolation=cv.INTER_AREA)
    button_areas = cv.selectROIs("Enter to confirm", img, True, False)
    print('button_areas =', button_areas)

    for r in button_areas:
        cv.rectangle(img, (r[0], r[1]), (r[0] + r[2], r[1] + r[3]), 255)
        ##    img = img[r[1]:r[1]+r[3], r[0]:r[0]+r[2]]
    ##    cv.imshow('Img', img)
    ##    cv.waitKey()

    cv.imshow('img', img)
    cv.waitKey()
    cv.destroyAllWindows()

    return button_areas
 def select_roi(self):
     self.set_button_false()  # 把视频暂停了
     if self.vth.frame is None:
         cap = cv2.VideoCapture(video_path)
         frame = self.vth.adjust_frame(cap.read()[1])
         cap.release()
     else:
         frame = self.vth.frame.copy()
     cv2.namedWindow('Select ROI', cv2.WINDOW_NORMAL)
     print('选择一个roi,按下space或enter键后确认选择,继续选择下一个roi,全部选择结束后按Esc键退出')
     bboxes = cv2.selectROIs("Select ROI",
                             frame,
                             fromCenter=False,
                             showCrosshair=True)
     cv2.destroyWindow('Select ROI')
     if not isinstance(bboxes, tuple):
         bboxes[:, 2:4] = bboxes[:, 0:2] + bboxes[:, 2:4]
         self.vth.CF.roi_list = bboxes
 def select_box(self):  # 手动绘制待跟踪目标
     self.set_button_false()  # 把视频暂停了
     if self.vth.frame is None:
         cap = cv2.VideoCapture(video_path)
         frame = self.vth.adjust_frame(cap.read()[1])
         cap.release()
     else:
         frame = self.vth.frame.copy()
     cv2.namedWindow('MultiTracker', cv2.WINDOW_NORMAL)
     print('选择一个目标,按下space或enter键后确认选择,继续选择下一个目标,全部选择结束后按Esc键退出')
     bboxes = cv2.selectROIs("MultiTracker",
                             frame,
                             fromCenter=False,
                             showCrosshair=True)
     cv2.destroyWindow('MultiTracker')
     for bbox in bboxes:
         self.vth.CF.multiTracker.add(cv2.TrackerKCF_create(), frame,
                                      tuple(bbox))
         self.vth.CF.car_num += 1
    def manual_face_selection(self, image):
        '''
    Handles the manual selection of faces bounding boxes in case the Viola-Jones algorithm
    misses them. Once the user selects the rectangles, these are obscured with the same
    policy applied fo the others.
    '''
        fromCenter = False
        showCrossHair = True
        rois = cv2.selectROIs("", image, showCrossHair, fromCenter)

        for roi in rois:
            self.final_image = cv2.rectangle(
                self.final_image, (roi[0], roi[1]),
                (roi[0] + roi[2], roi[1] + roi[3]), (0, 255, 0), 2)
            self.final_image[roi[1]:roi[1] + roi[3],
                             roi[0]:roi[0] + roi[2]] = cv2.blur(
                                 self.final_image[roi[1]:roi[1] + roi[3],
                                                  roi[0]:roi[0] + roi[2]],
                                 (40, 40))
def initialVideo(filename, t_type='KCF'):
    video = cv2.VideoCapture(filename)
    if filename == 0:
        while True:
            ret, frame = video.read()
            cv2.imshow("Press A to start", frame)
            k = cv2.waitKey(1)
            if k == ord('a'):
                cv2.destroyAllWindows()
                break
    success, firstframe = video.read()
    multiTracker = []
    boxes = cv2.selectROIs("Select", firstframe, False, False)

    for box in boxes:
        box = tuple(box)
        tracker = TrackerDefine(t_type)
        tracker.init(firstframe, box)
        multiTracker.append(tracker)
    cv2.destroyAllWindows()
    return video, multiTracker[:3], boxes[:3], firstframe
예제 #24
0
 def getRoisDetectionImage(self,image):
     
     ROIs = cv2.selectROIs("Select Rois",image)
     #print rectangle points of selected roi
     print(ROIs)
     #Crop selected roi ffrom raw image
     #counter to save image with different name
     crop_number=0 
     #loop over every bounding box save in array "ROIs"
     for rect in ROIs:
         x1=rect[0]
         y1=rect[1]
         x2=rect[2]
         y2=rect[3]
         
         #crop roi from original image
         img_crop=image[y1:y1+y2,x1:x1+x2]
         cv2.imwrite("crop"+str(crop_number)+".jpeg",img_crop)
         #show cropped image
                 
         crop_number+=1
def createSel(img):
    '''
    Parameters
    ----------
    img : path to the image on wich to perform the ROI selection

    Returns
    -------
    imgCrop : the cropped image, as an array (cv2 or numpy)
    Coords : the coordinates of the selection as follows (row, row+rowheight, col, col+colwidth)
    '''
    #cv2.startWindowThread()
    #img = cv2.imread(img)
    #band_dict = get_band([band_id],folder)
    #img = band_dict[band_id]
    ROIs = cv2.selectROIs(
        "Select the ROI : Click and drag the mouse (top left to bottom right) and press Enter, or c to cancel",
        img)
    coords_list = list()
    #print(ROIs)
    for ROI in ROIs:
        #imgCrop = img[int(ROI[1]):int(ROI[1]+ROI[3]), int(ROI[0]):int(ROI[0]+ROI[2])]
        coords_list.append([
            int(ROI[1]),
            int(ROI[1] + ROI[3]),
            int(ROI[0]),
            int(ROI[0] + ROI[2])
        ])
        #cv2.imshow("Image", imgCrop)
        #cv2.waitKey(0)
        #cv2.destroyAllWindows()
    #print(Coords_list)
    cv2.destroyAllWindows()

    #label = create_label(img, coords_list, False)

    #if save:
    #    path = save_label(label, band_dict['folder'])
    print(coords_list)
    return coords_list
def MouseRoIVideo(cap):
    """
    openfaceのlandmarkを使って,顔領域を選択し平均化されたRGBを返す
    """
    # マウスイベント
    winname = 'Image'
    ret, image = cap.read()
    rois = cv2.selectROIs(winname, image, False) # x,y,w,h
    cv2.destroyAllWindows()
    for r in rois:
        print("x:{}, y:{}, w:{}, h:{}".format(r[0],r[1],r[2],r[3]))
 
    # loop from first to last frame
    for i in range(int(cap.get(cv2.CAP_PROP_FRAME_COUNT))-1):
        j = 0
        #for fname in files:
        print("Frame: {}/{}".format(i,cap.get(cv2.CAP_PROP_FRAME_COUNT)))
        ret, frame = cap.read()
        for r in rois:
            img_roi = frame[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])]
            if j == 0:
                ave_rgb_roi = AveragedRGB(img_roi)
            else:
                ave_rgb_roi = np.concatenate([ave_rgb_roi,AveragedRGB(img_roi)], axis=1)
            j = j+1
    
        if i == 0:
            rgb_components = ave_rgb_roi
        else:   
            rgb_components = np.concatenate([rgb_components, ave_rgb_roi], axis=0)

        # cv2.imshow("frame", mask_img)
        i = i + 1
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        print(i)

    cv2.destroyAllWindows()
    return rgb_components
예제 #27
0
def label_dataset(num_of_imgs: int):
    """
    A function using selectROI to label stream of images and saves it as jpg image.
    :param num_of_imgs (int): Number of images to label
   """

    for i in range(num_of_imgs):
        image_name = "TestingImages/" + str(i) + ".jpg"
        img_raw = cv2.imread(image_name)
        cv2.imshow("IMAGE " + str(i), img_raw)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        print("Enter number of regions (N):")
        num_of_reg = int(input())
        print("Number of regions = " + str(num_of_reg) +
              ". \n Create rectangles and after each rectangle press ENTER."
              " When done, press ESC to finish labeling this region. "
              "Repeat for each region.")
        labels_arr = np.zeros((img_raw.shape[0], img_raw.shape[1]))
        for label_id in range(1, num_of_reg + 1):
            print("Label Region #" + str(label_id))
            while True:
                boundingBoxes = cv2.selectROIs(
                    "LABEL REGION #" + str(label_id), img_raw)
                if not isinstance(boundingBoxes, tuple):
                    print("Region " + str(label_id) + " labeled")
                    for row in boundingBoxes:
                        labels_arr[row[1]:row[1] + row[3], row[0]:row[0] +
                                   row[2]] = label_id / num_of_reg
                    cv2.destroyAllWindows()
                    break
                else:
                    print("No Region Selected. Please select Region " +
                          str(label_id))
        cv2.imshow("Labels Array", labels_arr)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        cv2.imwrite("TestingImages/" + str(i) + "_label.jpg", labels_arr * 255)
        np.savez("TestingImages/" + str(i) + "_label", labels_arr)
예제 #28
0
    def tracker_init(self, image):
        """
        用于进行目标跟踪初始化
        都采用KCF的方法进行跟踪,其他的方法并不好用
        :param image: 初始化的图片
        :param track_method: 跟踪算法(默认为KCF)
        :return:
        """
        #每一次初始化,都把以前的跟踪目标给重置,要不然越add越多
        self.tracker = cv.MultiTracker_create()
        category_num = 10  #默认最多不超过10个类
        #1:进行bboxes的选择
        cv.namedWindow("ROI", cv.WINDOW_FULLSCREEN)
        select_bboxes = cv.selectROIs("ROI", image)
        bboxes = []

        #1.1bboxes中的所有bbox转成tuple类型
        for bbox in select_bboxes:
            x, y, w, h = bbox
            bboxes.append((x, y, w, h))

        #2:输入跟踪类别id
        print("请在图片中输入种类id")
        while True:
            info_input = cv.waitKey()
            info_input = int(info_input) - 48
            if -1 < info_input < category_num:  #在所有种类中则完成输入
                self.tracker_category_id = info_input
                break

            else:  #避免输入其他错误参数
                print("请输入一个介于0到{}之间的数字".format(category_num))

        #3:进行目标添加
        for bbox in bboxes:
            self.tracker.add(cv.TrackerKCF_create(), image, bbox)
        cv.destroyWindow("ROI")
        return bboxes
예제 #29
0
    def select_rois_over_image(cls, im, save_to, delimiter, quotechar,
                               quoting):
        """Select ROIs over a ndarray image.

        Args:
            im (ndarray): image to select ROIs over.
            save_to (str): csv file path to save ROIs data to.
            delimiter (str): delimiter.
            quotechar (str): quote char.
            quoting (csv.QUOTE_xxx constant): quoting instruction.
        """
        print("------------------------------------------------------------")
        print("If there are no ROIs being selected,")
        print("Pressing ESC will create 1 ROI with the size of whole image.")
        print("------------------------------------------------------------")
        rois = cv.selectROIs("Select ROIs", im)
        if len(rois) == 0:
            h, w, __ = im.shape
            rois = [[0, 0, w, h]]

        with open(save_to, "w+", newline="") as csvfile:
            writer = csv.DictWriter(
                csvfile,
                fieldnames=cls.default.keys(),
                delimiter=delimiter,
                quotechar=quotechar,
                quoting=quoting,
            )
            writer.writeheader()

            print("ROIs data:")
            for roi_n, roi_val in enumerate(rois):
                x, y, w, h = roi_val
                roi_data = cls.create_roi_data([roi_n, x, y, w, h])
                cls.add_default(roi_data)

                writer.writerow(roi_data)
                print(roi_data)
예제 #30
0
def annotateImages(dir, labels):
	for path in os.listdir(dir):
		# read and display next image in directory
		img = cv2.imread(os.path.join(dir, path))
		cv2.imshow(path, img)

		# allow user to select multiple regions of interest
		boxes = cv2.selectROIs(path, img, FROM_CENTER, SHOW_CROSSHAIR)
		cv2.destroyAllWindows()

		# allow user to label each box drawn
		for box in boxes:
			root = tkinter.Tk() 

			# show image within box in window with dropdown to select label
			box_img = img[box[1]:box[1]+box[3], box[0]:box[0]+box[2]]
			box_img = ImageTk.PhotoImage(image=Image.fromarray(box_img))
  
			canvas = tkinter.Canvas(root, width=300, height=300)      
			canvas.pack()         
			canvas.create_image(20,20, anchor="nw", image=box_img)     			
			
			root.mainloop()