def drawQuarterCircle(img,
                      color,
                      center=None,
                      axes=(40, 40),
                      angle=0,
                      sAngle=None,
                      eAngle=None,
                      thic=-1):
    dir = random.randint(1, 4)
    if center == None:
        #Quadrant 1
        if dir == 1:
            center = (5, 44)
            sAngle = 270
            eAngle = 360
        #Quadrant 2
        elif dir == 2:
            center = (44, 44)
            sAngle = 180
            eAngle = 270
        #Quadrant 3
        elif dir == 3:
            center = (44, 5)
            sAngle = 90
            eAngle = 180
        #Quadrant 4
        else:
            center = (5, 5)
            sAngle = 0
            eAngle = 90
    cv2.ellipse(img, center, axes, angle, sAngle, eAngle, color, thic)
def create_emoticon():
    emoticon = np.zeros([512, 512, 3], np.uint8)
    emoticon = cv2.circle(emoticon, (256, 256), 200, (0, 215, 255), -1)
    emoticon = cv2.ellipse(emoticon, (166, 200), (40, 30), 90, 0, 360,
                           (0, 0, 0), -1)
    emoticon = cv2.ellipse(emoticon, (166, 200), (40, 30), 90, 0, 360,
                           (255, 255, 255), 1)
    emoticon = cv2.ellipse(emoticon, (346, 200), (40, 30), 90, 0, 360,
                           (0, 0, 0), -1)
    emoticon = cv2.ellipse(emoticon, (346, 200), (40, 30), 90, 0, 360,
                           (255, 255, 255), 1)
    emoticon = cv2.circle(emoticon, (180, 175), 7, (255, 255, 255), -1)
    emoticon = cv2.circle(emoticon, (360, 175), 7, (255, 255, 255), -1)
    pts = [(130, 260), (150, 390), (362, 390), (382, 260), (256, 248)]
    cv2.fillPoly(emoticon, np.array([pts]), (208, 224, 64))
    cv2.polylines(emoticon, np.array([pts]), True, (255, 255, 255), 2)
    cv2.line(emoticon, (150, 290), (362, 290), (209, 206, 0), 2)
    cv2.line(emoticon, (155, 330), (357, 330), (209, 206, 0), 2)
    cv2.line(emoticon, (160, 360), (352, 360), (209, 206, 0), 2)
    cv2.line(emoticon, (130, 260), (65, 200), (255, 255, 255), 2)
    cv2.line(emoticon, (382, 260), (447, 200), (255, 255, 255), 2)
    cv2.line(emoticon, (150, 390), (125, 405), (255, 255, 255), 2)
    cv2.line(emoticon, (362, 390), (387, 405), (255, 255, 255), 2)
    cv2.imshow('emoticon', emoticon)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
Пример #3
0
    def describe(self, image):
        # convert the image to the HSV color space and initialize
        # the features used to quantify the image
        image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
        features = []
        # grab the dimensions and compute the center of the image
        (h, w) = image.shape[:2]
        (cX, cY) = (int(w * 0.5), int(h * 0.5))

        # divide the image into four rectangles/segments (top-left,
        # top-right, bottom-right, bottom-left)
        segments = [(0, cX, 0, cY), (cX, w, 0, cY), (cX, w, cY, h),
                    (0, cX, cY, h)]
        # construct an elliptical mask representing the center of the
        # image
        (axesX, axesY) = (int(w * 0.75) // 2, int(h * 0.75) // 2)
        ellipMask = np.zeros(image.shape[:2], dtype="uint8")
        cv2.ellipse(ellipMask, (cX, cY), (axesX, axesY), 0, 0, 360, 255, -1)
        # loop over the segments
        for (startX, endX, startY, endY) in segments:
            # construct a mask for each corner of the image, subtracting
            # the elliptical center from it
            cornerMask = np.zeros(image.shape[:2], dtype="uint8")
            cv2.rectangle(cornerMask, (startX, startY), (endX, endY), 255, -1)
            cornerMask = cv2.subtract(cornerMask, ellipMask)
            # extract a color histogram from the image, then update the
            # feature vector
            hist = self.histogram(image, cornerMask)
            features.extend(hist)
        # extract a color histogram from the elliptical region and
        # update the feature vector
        hist = self.histogram(image, ellipMask)
        features.extend(hist)
        # return the feature vector
        return features
Пример #4
0
def detectAndDisplay(frame):
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    frame_gray = cv2.equalizeHist(frame_gray)
    # Detectar faces
    # Divide a imagem em diversos retângulos e retorna uma lista com eles
    faces = face_cascade.detectMultiScale(frame_gray)
    for (x, y, w, h) in faces:
        center = (x + w // 2, y + h // 2)
        # Elipses rosas
        frame = cv2.ellipse(frame, center, (w // 2, h // 2), 0, 0, 360,
                            (255, 0, 255), 4)
        faceROI = frame_gray[y:y + h, x:x + w]

        # Em cada face, detectar olhos
        eyes = eyes_cascade.detectMultiScale(faceROI)
        for (x2, y2, w2, h2) in eyes:
            eye_center = (x + x2 + w2 // 2, y + y2 + h2 // 2)
            radius = int(round((w2 + h2) * 0.25))
            # Circulos azuis
            frame = cv2.circle(frame, eye_center, radius, (255, 0, 0), 4)

    # Frame invertido horizontalmente por questão de estética =)
    frame = cv2.flip(frame, 1)
    cv2.imshow('Deteccao de Face e Olho', frame)
    return frame
Пример #5
0
def choose_target_point(skel):
    """ Selects a target poitn from skeleton for pure pursuit.

    Draws a ellipse and applies an and operation to the ellipse with the skel.
    Then returns a point that has least distance with the center of the
    ellipse.

    Args:
        skel: skeleton of trajectory.

    Returns:
        target_point: target point for pure pursuit.

    """
    width = skel.shape[1]
    height = skel.shape[0]

    img = np.zeros((height, width), dtype=np.uint8)

    ellipse = cv.ellipse(img,
                         center=(width // 2, height),
                         axes=(width // 3, height // 2),
                         angle=0,
                         startAngle=180,
                         endAngle=360,
                         color=255,
                         thickness=1)

    img_points = np.bitwise_and(skel, ellipse)

    _, contours, _ = cv.findContours(img_points,
                                     mode=cv.RETR_EXTERNAL,
                                     method=cv.CHAIN_APPROX_NONE)

    discrete_points = []

    img_DEBUG = np.zeros((height, width, 3), dtype=np.uint8)

    img_DEBUG[:, :, 0] = skel
    img_DEBUG[:, :, 1] = img_points

    if DEBUG:
        cv.imwrite("img_DEBUG.jpg", img_DEBUG)

    # cv.waitKey(200)

    for contour in contours:
        if contour.size == 2:
            discrete_points.append(np.squeeze(contour))
        else:
            pass

    discrete_points = sorted(discrete_points,
                             key=lambda x: (x[0] - width // 2)**2 +
                             (x[1] - height)**2)

    if len(discrete_points) != 0:
        return discrete_points[0], width, height, img_DEBUG
    else:
        return [371, 0], width, height, img_DEBUG
Пример #6
0
    def __draw_ellipse(self, image):
        params = self.dict_parameters
        keys = params.keys()
        assert all(
            key in keys for key in
            ['center', 'axes', 'angle', 'startAngle', 'endAngle', 'color'])

        cv2.ellipse(image,
                    center=params['center'],
                    axes=params['axes'],
                    angle=params['angle'],
                    startAngle=params['startAngle'],
                    endAngle=params['endAngle'],
                    color=params['color'],
                    thickness=params.get('thickness') or 1,
                    lineType=params.get('lineType') or 8,
                    shift=params.get('shift') or 0)
def drawSemiCircle(img,
                   color,
                   center=None,
                   axes=(25, 25),
                   angle=0,
                   sAngle=0,
                   eAngle=None,
                   thic=-1):
    dir = random.randint(1, 2)
    if center == None:
        if dir == 1:
            center = (24, 14)
            eAngle = 180
        else:
            center = (24, 35)
            eAngle = -180
    cv2.ellipse(img, center, axes, angle, sAngle, eAngle, color, thic)
Пример #8
0
    def _update_agents_on_map(self, i, temp_pos_x, temp_pos_y):

        color_b, color_g, color_r = self._agent_color_list[i]

        self._gloabal_grid_with_agents = cv2.ellipse(self._global_grid_display,(temp_pos_x,temp_pos_y),\
                                            (10,10),0,15,345,(color_b,color_g,color_r),-1)

        self._known_grid_with_agents = cv2.ellipse(self._known_grid_display,(temp_pos_x,temp_pos_y),\
                                            (10,10),0,15,345,(color_b,color_g,color_r),-1)

        string_to_add = "Agent:" + str(i) + ", region:" + str(
            self._region_col[i])
        self._grid_with_regions_display = cv2.putText(
            self._grid_with_regions_display, string_to_add,
            (temp_pos_x, temp_pos_y + 25), self._font, 0.5, (0, 0, 0), 2,
            cv2.LINE_AA)

        self._grid_with_agents_and_regions = cv2.ellipse(
            self._grid_with_regions_display, (temp_pos_x, temp_pos_y),
            (10, 10), 0, 15, 345, (color_b, color_g, color_r), -1)
Пример #9
0
    def show(image):
        result = Recognition().recognize(image)

        polygon = []
        for qr in result['qr']:
            pts = np.array(
                list(
                    map(lambda point: [point.x, point.y],
                        qr['location'].points)), np.int32).reshape((-1, 1, 2))
            polygon.append(pts)

        for ring in result['rings']:
            cv2.ellipse(img=image,
                        center=(int(ring.center.x), int(ring.center.y)),
                        axes=(int(ring.maxLength), int(ring.minLength)),
                        angle=ring.angle,
                        color=(0, 255, 255),
                        startAngle=0,
                        endAngle=360)

        cv2.polylines(image, polygon, True, (0, 255, 255))
        cv2.imshow('detected circles', image)
        cv2.moveWindow('detected circles', 20, 20)
Пример #10
0
def load_mask(annos, datadir, imgid, imgdata, rois):
    img = annos["imgs"][imgid]
    mask = np.zeros(imgdata.shape[:-1])
    mask_poly = np.zeros(imgdata.shape[:-1])
    mask_ellipse = np.zeros(imgdata.shape[:-1])
    for obj in img['objects']:
        box = obj['bbox']
        cv2.rectangle(mask, (int(box['xmin']), int(box['ymin'])), (int(box['xmax']), int(box['ymax'])), 1, -1)
        if 'polygon' in obj and len(obj['polygon'])>0:
            pts = np.array(obj['polygon'])
            cv2.fillPoly(mask_poly, [pts.astype(np.int32)], 1)
            rois.append(pts)
        else:
            cv2.rectangle(mask_poly, (int(box['xmin']), int(box['ymin'])), (int(box['xmax']), int(box['ymax'])), 1, -1)
        if 'ellipse' in obj:
            rbox = obj['ellipse']
            rbox = ((rbox[0][0], rbox[0][1]), (rbox[1][0], rbox[1][1]), rbox[2])
            rois.append(rbox)
            cv2.ellipse(mask_ellipse, rbox, 1, -1)
        else:
            cv2.rectangle(mask_ellipse, (int(box['xmin']), int(box['ymin'])), (int(box['xmax']), int(box['ymax'])), 1, -1)
    mask = np.multiply(np.multiply(mask,mask_poly),mask_ellipse)
    return mask
Пример #11
0
    def draw_circle(self, img, descirptor_in_use):
        """获取外接轮廓

        :param res: 输入图像,傅里叶描述子
        :return: 重绘图像
        """
        contour_reconstruct = np.fft.ifft(descirptor_in_use)  # 傅里叶反变换
        contour_reconstruct = np.array(
            [contour_reconstruct.real, contour_reconstruct.imag])
        contour_reconstruct = np.transpose(contour_reconstruct)  # 转换矩阵
        contour_reconstruct = np.expand_dims(contour_reconstruct,
                                             axis=1)  # 改变数组维度在axis=1轴上加1
        if contour_reconstruct.min() < 0:
            contour_reconstruct -= contour_reconstruct.min()
        contour_reconstruct *= img.shape[0] / contour_reconstruct.max()
        contour_reconstruct = contour_reconstruct.astype(np.int32, copy=False)

        x, y, w, h = cv2.boundingRect(contour_reconstruct)  # 外接矩形
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 225, 0), 3)
        rect = cv2.minAreaRect(contour_reconstruct)  # 最小外接矩形
        box = np.int0(cv2.boxPoints(rect))  # 矩形的四个角点取整
        cv2.drawContours(img, [box], 0, (0, 255, 255), 3)
        (x, y), radius = cv2.minEnclosingCircle(contour_reconstruct)  # 最小外接圆
        (x, y, radius) = np.int0((x, y, radius))  # 圆心和半径取整
        cv2.circle(img, (x, y), radius, (0, 255, 0), 2)
        ellipse = cv2.fitEllipse(contour_reconstruct)  # 拟合椭圆
        cv2.ellipse(img, ellipse, (0, 0, 255), 2)

        df = pd.DataFrame(np.random.rand(10, 4),
                          columns=[u'外接矩形', u'最小外接矩阵', u'外接圆', u'椭圆'])
        fig = df.plot(figsize=(6, 6))  # 创建图表对象,并复制给fig
        plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        plt.xlabel(u'图像轮廓', fontsize=20)

        plt.show()
        return img
Пример #12
0
    def detect_ransac(self,
                      img,
                      outlier_rate=0.4,
                      iterations=1000,
                      draw_ellipse=False):
        '''
        Detect valve center with RANSAC ellipse fitting algorithm.

        @img:
            np.array, input image.
        @outlier_rate
            float, rate of pre-estimated outliers in fitting points, should be larger than 0 and smaller than 1.0.
        @iterations
            int, positive int, which means the total iterations of RANSAC algorithm.
        @return
            (np.array, ellipse), image with fitted ellipse and ellipse parameters.
            Parameters are exactly the same as the return values of OpenCV fitEllipse() function.
        '''
        edge = self._get_saturation_edge(img)
        points = self._get_points(edge)

        # traditional fitting
        # elps = cv.fitEllipse(points)
        # center, _, _ = elps
        # x = int(center[0])
        # y = int(center[1])
        # img = cv.ellipse(img, elps, color=(0,255,0), thickness=1)
        # img = cv.circle(img, (x, y), 2, (0,255,0), cv.FILLED)

        # ransac
        ellipse = self._fit_ellipse_ransac(points, outlier_rate, iterations)
        center, params, _ = ellipse
        x = int(center[0])
        y = int(center[1])
        if draw_ellipse:
            img = cv.ellipse(img, ellipse, color=(0, 255, 255), thickness=1)
            img = cv.circle(img, (x, y), 2, (0, 255, 255), cv.FILLED)
        # print('ratio of axis(short/long):{0:.3f}'.format(params[0]/params[1]))
        return img, ellipse
    def place_agents_on_grid_with_info_of_assigned_region(self):

        self.grid_with_region()
        temp_grid = copy.copy(self._grid_with_regions)

        font = cv2.FONT_HERSHEY_SIMPLEX

        for i in range(self._no_of_agents):

            temp_agent_pos = self._agenthandler.get_pos_of_agent(i)
            a = np.array([temp_agent_pos['x'], temp_agent_pos['y']])
            string_to_add = "Agent:" + str(i) + ", region:" + str(
                self._col_ind[i])
            temp_grid = cv2.putText(temp_grid, string_to_add,
                                    (a[0], a[1] + 25), font, 0.5, (0, 0, 0), 2,
                                    cv2.LINE_AA)

            color_b, color_g, color_r = self._agent_color_list[i]

            temp_grid = cv2.ellipse(temp_grid, (a[0], a[1]), (10, 10), 0, 15,
                                    345, (color_b, color_g, color_r), -1)

        self._grid_with_regions_and_agents = temp_grid
Пример #14
0
    while cap.isOpened():
        ret, frame = cap.read()
        if ret:
            t0 = time.time()
            frame = cv2.flip(frame, 1)
            cropped = frame[206 - 100:206 + 100, 256 - 100:256 + 100]

            bboxes = detector.detect(cropped)

            for box in bboxes:
                x, y, width, height = box
                x, y = x + 256 - 100, y + 206 - 100
                x2, y2 = x + width, y + height
                cv2.rectangle(frame, (x, y), (x2, y2), (0, 100, 100), 5)

            cv2.ellipse(frame, (256, 206), (100, 100), 0, 0, 360, 50, 5)
            cv2.rectangle(frame, (256 - 100, 206 - 100),
                          (256 + 100, 206 + 100), (0, 0, 255), 10)
            t1 = time.time()
            font = cv2.FONT_HERSHEY_PLAIN
            org = (50, 50)
            fontScale = 1
            color = (255, 0, 0)

            thickness = 2
            message = f'{round(t1-t0, 3)} sec per frame'

            cv2.putText(frame, message, org, font, fontScale, color, thickness,
                        cv2.LINE_AA)
            cv2.imshow("preview", frame)
            # out.write(frame)
Пример #15
0
# Rotated Rectangle is drawn with minimum area, so it considers the rotation also. The function used is cv2.minAreaRect(). It returns a Box2D structure which contains following detals - (top-left corner(x, y), (width, height), angle of rotation). But to draw this rectangle, we need 4 corners of the rectangle. It is obtained by the function cv2.boxPoints()
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
boundingRect = cv2.drawContours(img_rgb, [box], 0, (0, 0, 255), 2)

# cv2.minEnclosingCircle() find the circumcircle of an object. It is a circle which completely covers the object with minimum area.
(x, y), radius = cv2.minEnclosingCircle(cnt)
center = (int(x), int(y))
radius = int(radius)
circumcircle = cv2.circle(img_rgb2, center, radius, (0, 255, 0), 2)

# To fit an ellipse to an object, use the function cv2.fitEllipse(). It returns the rotated rectangle in which the ellipse is inscribed.
ellipse = cv2.fitEllipse(cnt)
fit = cv2.ellipse(img_rgb3, ellipse, (0, 255, 0), 2)

# Similarly we can fit a line to a set of points. Below image contains a set of white points. We can approximate a straight line to it.
rows, cols = img.shape[:2]
[vx, vy, x, y] = cv2.fitLine(cnt, cv2.DIST_L2, 0, 0.01, 0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((cols-x)*vy/vx)+y)
fit = cv2.line(img_rgb3, (cols-1, righty), (0, lefty), (0, 255, 0), 2)


plt.subplot(2, 2, 1), plt.imshow(img, cmap='gray')
plt.title('Original'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 2, 2), plt.imshow(boundingRect, cmap='gray')
plt.title('boundingRect and RotatedRect'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 2, 3), plt.imshow(circumcircle, cmap='gray')
plt.title('minEnclosingCircle'), plt.xticks([]), plt.yticks([])
Пример #16
0
        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),
                    2, cv2.LINE_AA)
        cv2.putText(frame, "Prediction", (0, 50), font, 0.5, (0, 0, 255), 2,
                    cv2.LINE_AA)

        rgbr = np.floor_divide(colorMask, REDU)
        r, g, b = rgbr.transpose(2, 0, 1)
        l = his[r, g, b]
        maxl = l.max()
        aa = np.clip((l * l / maxl * 255), 0, 255).astype(np.uint8)

        (rb, roiBox) = cv2.CamShift(l, roiBox, termination)
        cv2.ellipse(frame, rb, (0, 255, 0), 2)

        xo = int(roiBox[0] + roiBox[2] / 2)
        yo = int(roiBox[1] + roiBox[3] / 2)
        error = (roiBox[3])

        if (yo < error or fgmask.sum() < 50):
            mu, P, pred = kalman(mu, P, F, Q, B, a, None, H, R)
            m = "None"
            mm = False
        else:
            mu, P, pred = kalman(mu, P, F, Q, B, a, np.array([xo, yo]), H, R)
            m = "normal"
            mm = True

        if (mm):
Пример #17
0
def convex(ImgNo, defThr=127):
    img = cv2.imread(impDef.select_img(ImgNo))
    img2 = img.copy()
    imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    ret, thr = cv2.threshold(imgray, defThr, 255, 0)
    contours, _ = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    #    cntI = 80
    #    for i in contours:
    #        cnt0 = contours[cntI]
    #        cv2.drawContours(img, [cnt0], 0, (0, 0, 255), 2)
    #        cv2.imshow('contour', img)
    #        print('cntI = ', cntI)
    #        impDef.close_window( )
    #        cntI = cntI+1

    cnt = contours[88]

    #cv2.moments() 함수를 이용해 한반도의 무게 중심 좌표를 구합니다
    mmt = cv2.moments(cnt)
    cx = int(mmt['m10'] / mmt['m00'])
    cy = int(mmt['m01'] / mmt['m00'])

    x, y, w, h = cv2.boundingRect(cnt)
    korea_rect_area = w * h
    korea_area = cv2.contourArea(cnt)
    hull = cv2.convexHull(cnt)
    hull_area = cv2.contourArea(hull)
    ellipse = cv2.fitEllipse(cnt)

    aspect_ratio = w / h
    extent = korea_area / korea_rect_area
    solidity = korea_area / hull_area

    print('대한민국 Aspect Ratio : \t%.3f' % aspect_ratio)
    print('대한미국 Extent : \t%.3f' % extent)
    print('대한민국 Solidity : \t%.3f' % solidity)
    print('대한민국 Orientation : \t%.3f' % ellipse[2])
    # Orientation of Korea는 한반도 Contour에 최적 타원의 방향입니다.
    # 이 값은 cv2.fitEllipse() 함수의 리턴값인 ellipse의 3번째 멤버인 ellipse[2] 값이며,
    # 수직방향을 기준으로 타원이 회전한 각도를 나타냅니다.

    equivalent_diameter = np.sqrt(4 * korea_area / np.pi)
    korea_radius = int(equivalent_diameter / 2)

    # 한반도 무게 중심을 빨간색 원으로 표시를 합니다.
    # 그리고 이 무게중심을 중심으로 한 한반도와 면적이 동일한 빨간색 원을 그렸습니다.
    cv2.circle(img, (cx, cy), 3, (0, 0, 255), -1)
    cv2.circle(img, (cx, cy), korea_radius, (0, 0, 255), 2)
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
    cv2.ellipse(img, ellipse, (50, 50, 50), 2)

    # 각 방위의 끝 지점(최 남단, 최 북단,....)
    leftmost = tuple(cnt[cnt[:, :, 0].argmin()][0])
    rightmost = tuple(cnt[cnt[:, :, 0].argmax()][0])
    topmost = tuple(cnt[cnt[:, :, 1].argmin()][0])
    bottommost = tuple(cnt[cnt[:, :, 1].argmax()][0])

    print('leftmost = ', leftmost)
    print('rightmost = ', rightmost)
    print('topmost = ', topmost)
    print('bottommost = ', bottommost)

    img = cv2.line(img, leftmost, leftmost, (10, 10, 10), 10)
    img = cv2.line(img, rightmost, rightmost, (10, 10, 10), 10)
    img = cv2.line(img, topmost, topmost, (10, 10, 10), 10)
    img = cv2.line(img, bottommost, bottommost, (10, 10, 10), 10)

    cv2.imshow('Korea Features', img)

    impDef.close_window()
Пример #18
0
    def start_tracking(self):
        # Iterate until the user presses the Esc key
        while True:
            # Capture the frame from webcam
            _, self.frame = self.cap.read()

            # Resize the input frame
            self.frame = cv.resize(self.frame,
                                   None,
                                   fx=self.scaling_factor,
                                   fy=self.scaling_factor,
                                   interpolation=cv.INTER_AREA)

            # Create a copy of the frame
            vis = self.frame.copy()

            # Convert the frame to HSV colorspace
            hsv = cv.cvtColor(self.frame, cv.COLOR_BGR2HSV)

            # Create the mask based on predefined thresholds
            mask = cv.inRange(hsv, np.array((0., 60., 32.)),
                              np.array((180., 255., 255.)))

            # Check if the user has selected the region
            if self.selection:
                # Extract the coordinates of the selected rectangle
                x0, y0, x1, y1 = self.selection

                # Extract the tracking window
                self.track_window = (x0, y0, x1 - x0, y1 - y0)

                # Extract the regions of interest
                hsv_roi = hsv[y0:y1, x0:x1]
                mask_roi = mask[y0:y1, x0:x1]

                # Compute the histogram of the region of
                # interest in the HSV image using the mask
                hist = cv.calcHist([hsv_roi], [0], mask_roi, [16], [0, 180])

                # Normalize and reshape the histogram
                cv.normalize(hist, hist, 0, 255, cv.NORM_MINMAX)
                self.hist = hist.reshape(-1)

                # Extract the region of interest from the frame
                vis_roi = vis[y0:y1, x0:x1]

                # Compute the image negative (for display only)
                cv.bitwise_not(vis_roi, vis_roi)
                vis[mask == 0] = 0

            # Check if the system in the "tracking" mode
            if self.tracking_state == 1:
                # Reset the selection variable
                self.selection = None

                # Compute the histogram back projection
                hsv_backproj = cv.calcBackProject([hsv], [0], self.hist,
                                                  [0, 180], 1)

                # Compute bitwise AND between histogram
                # backprojection and the mask
                hsv_backproj &= mask

                # Define termination criteria for the tracker
                term_crit = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10,
                             1)

                # Apply CAMShift on 'hsv_backproj'
                track_box, self.track_window = cv.CamShift(
                    hsv_backproj, self.track_window, term_crit)

                # Draw an ellipse around the object
                cv.ellipse(vis, track_box, (0, 255, 0), 2)

            # Show the output live video
            cv.imshow('Object Tracker', vis)

            # Stop if the user hits the 'Esc' key
            c = cv.waitKey(5)
            if c == 27:
                break

        # Close all the windows
        cv.destroyAllWindows()
Пример #19
0
# 轉換為整數,還是不太懂int0,網路上說int0=intp(?
box = np.int0(box)
cv2.drawContours(originalImage, [box], 0, (0, 0, 255), 5)

# 擬合橢圓的最小外接橢圓形
ellipse = cv2.fitEllipse(cntb)
'''
fitEllipse回傳5個值
→ xc : x coordinate of the center
→ yc : y coordinate of the center
→ a : major semi-axis
→ b : minor semi-axis
→ theta : rotation angle
'''

cv2.ellipse(imgB, ellipse, (255, 0, 255), 5)
'''
void ellipse(Mat& img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
→ img(imgB):輸入圖,橢圓會畫在上面。
→ center(ellipse):圓心。
→ axes(ellipse):橢圓軸的尺寸。
→ angle(ellipse):旋轉角度,單位角度。
→ startAngle(ellipse):橢圓弧度起始角度,單位角度。
→ endAngle(ellipse):橢圓弧度結束角度,單位角度。
→ color(255, 0, 255):橢圓的顏色。
→ thickness(2):橢圓的邊線寬度,輸入負值或CV_FILLED代表填滿橢圓形 。
→ lineType(*):通道型態,可輸入8、4、CV_AA: 8->8通道連結。 4->4通道連結。 CV_AA->消除鋸齒(antialiased line),消除顯示器畫面線邊緣的凹凸鋸齒。
'''

# 擬合最小圓形外框
(x, y), radius = cv2.minEnclosingCircle(cntb)
Пример #20
0
rotatedRect = cv2.drawContours(img.copy(), [box], -1, (255,255,0),3)
cv2.imshow('rotatedRect',rotatedRect)

# Minimum Enclosing Circle

# Next we find the circumcircle of an object using the function cv2.minEnclosingCircle(). It is a circle which completely covers the object with minimum area.
(x,y),radius = cv2.minEnclosingCircle(cnt)
minEnclosCircle = cv2.circle(img.copy(), (int(x),int(y)), int(radius), (255,255,0), 2)
cv2.imshow('minEnclosCircle',minEnclosCircle)

# Fitting an Ellipse

# Next one is to fit an ellipse to an object. It returns the rotated rectangle in which the ellipse is inscribed.

ellipse = cv2.fitEllipse(cnt)
fitEllipse = cv2.ellipse(img.copy(),ellipse,(0,255,0),2)
cv2.imshow('fitEllipse',fitEllipse)

# Fitting a Line

# Similarly we can fit a line to a set of points. Below image contains a set of white points. We can approximate a straight line to it.
rows,cols = img.shape[:2]
[vx,vy,x,y] = cv2.fitLine(cnt, cv2.DIST_L2,0,0.01,0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((cols-x)*vy/vx)+y)
fitLine = cv2.line(img.copy(),(cols-1,righty),(0,lefty),(0,255,0),2)
cv2.imshow('fitLine',fitLine)

# hold window
cv2.waitKey(0)
cv2.destroyAllWindows()
Пример #21
0
def elongate_contour(contour, img_shape, extend_length):
    c_mask = np.zeros(img_shape, dtype=np.uint8)

    cv2.drawContours(c_mask, [contour], -1, 255, -1)

    rect = cv2.minAreaRect(contour)

    cx, cy = rect[0]
    w, h = rect[1]
    angle = rect[2]

    if w <= 1 or h <= 1 or extend_length < 0:
        return contour

    if isinstance(extend_length, float) and extend_length <= 1.0:
        extend_length = int(extend_length * max(w, h)) + 1

    if w > h:
        angle = angle - 90

    mat = cv2.getRotationMatrix2D((cx, cy), angle, 1.0)
    c_mask_rot = cv2.warpAffine(c_mask, mat, img_shape)
    c_mask_rot[c_mask_rot > 0] = 255

    y_locs = np.where(c_mask_rot > 0)[0]
    y_min = y_locs.min()
    y_max = y_locs.max()
    y_mid = int(np.round(np.average([y_min, y_max])))

    top_x_locs = np.where(c_mask_rot[y_min + 1, :] > 0)[0]
    mid_x_locs = np.where(c_mask_rot[y_mid, :] > 0)[0]
    bottom_x_locs = np.where(c_mask_rot[y_max - 1, :] > 0)[0]

    mid_x_min = mid_x_locs.min()
    mid_x_max = mid_x_locs.max()
    mid_x_mid = int(np.round(np.average([mid_x_min, mid_x_max])))
    mid_width = mid_x_max - mid_x_min

    if len(top_x_locs) > 0:
        top_x_min = top_x_locs.min()
        top_x_max = top_x_locs.max()
        top_x_mid = int(np.round(np.average([top_x_min, top_x_max])))
        extend_top = True
    else:
        extend_top = False

    if len(bottom_x_locs) > 0:
        bottom_x_min = bottom_x_locs.min()
        bottom_x_max = bottom_x_locs.max()
        bottom_x_mid = int(np.round(np.average([bottom_x_min, bottom_x_max])))
        extend_bottom = True
    else:
        extend_bottom = False

    mid_coord = (mid_x_mid, y_mid)
    new_c_mask_rot = c_mask_rot.copy()

    if extend_top:
        top_coord = (top_x_mid, y_min)

        top_angle = np.math.atan2(top_coord[1] - mid_coord[1],
                                  top_coord[0] - mid_coord[0])
        top_angle = top_angle * 180 / np.pi

        cv2.ellipse(new_c_mask_rot, top_coord,
                    (extend_length, int(mid_width / 4)), top_angle, 0, 360,
                    255, -1)

    if extend_bottom:
        bottom_coord = (bottom_x_mid, y_max)

        bottom_angle = np.math.atan2(bottom_coord[1] - mid_coord[1],
                                     bottom_coord[0] - mid_coord[0])
        bottom_angle = bottom_angle * 180 / np.pi

        cv2.ellipse(new_c_mask_rot, bottom_coord,
                    (extend_length, int(mid_width / 4)), bottom_angle, 0, 360,
                    255, -1)

    inv_mat = cv2.getRotationMatrix2D((cx, cy), -angle, 1.0)
    c_mask_new = cv2.warpAffine(new_c_mask_rot, inv_mat, img_shape)

    # fix interpolation artifacts
    c_mask_new[c_mask_new > 0] = 255

    contours, hierarchy = cv2.findContours(c_mask_new.copy(),
                                           cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_SIMPLE)

    return contours[0]
Пример #22
0
# -*- coding: utf-8 -*-
# !/usr/bin/env python

import numpy as np
from cv2 import cv2 as cv

# 创建黑色的图像
img = np.zeros((512, 512, 3), np.uint8)
# 绘制一条厚度为5的蓝色对角线
cv.line(img, (0, 0), (511, 511), (255, 0, 0), 5)
cv.imshow("geometric", img)
cv.waitKey(0)
cv.destroyAllWindows()

# 创建黑色的图像
circle = np.zeros((512, 512, 3), np.uint8)
# 绘制 圆
cv.circle(circle, (447, 63), 63, (0, 0, 255), -1)
cv.imshow("circle", circle)
cv.waitKey(0)
cv.destroyAllWindows()

# 创建黑色的图像
ellipse = np.zeros((512, 512, 3), np.uint8)
# 绘制 椭圆
cv.ellipse(ellipse, (256, 256), (100, 50), 0, 0, 180, 255, -1)
cv.imshow("ellipse", ellipse)
cv.waitKey(0)
cv.destroyAllWindows()
# 图片 起点 终点 颜色RGB 粗细
cv2.line(img, (0, 0), (511, 511), (255, 255, 0), 1)
'''
画矩形
'''
cv2.rectangle(img, (0, 0), (510, 128), (0, 255, 0), 2)
'''
画圆
'''
# 圆心 半径 颜色 -1表实心
cv2.circle(img, (447, 63), 63, (0, 0, 255), -1)
'''
画椭圆
'''
# (中心点)(水平轴 垂直轴),角度,画出的起始度数,结束度数,颜色,粗细
cv2.ellipse(img, (256, 256), (100, 50), 0, 10, 360, (0, 255, 0), -1)
'''
画多边形
'''
pts = np.array([[400, 5], [200, 300], [150, 20], [500, 100]], np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.polylines(img, [pts], True, (255, 125, 0))
# 这里 reshape 的第一个参数为-1, 表明这一维的长度是根据后面的维度的计算出来的。
'''
添加文字
'''
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'LESVAY', (10, 500), font, 4, (255, 255, 255), 2)
'''
显示结果
'''
Пример #24
0
#arrowedline
img = cv2.arrowedLine(img, (0, 255), (255, 255), (255, 0, 0), 10)
#rectangle
img = cv2.rectangle(img, (344, 0), (418, 120), (0, 255, 0),
                    -1)  #-1 gives filled shape
#circle
img = cv2.circle(img, (210, 210), 50, (217, 200, 0), 10)
#put text on image
font = cv2.FONT_HERSHEY_COMPLEX
img = cv2.putText(img, 'Lena', (300, 350), font, 2, (255, 255, 0), 2,
                  cv2.LINE_AA)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

#Create blank image
image = np.zeros([512, 512, 3], np.uint8)
#draw ellipse
image = cv2.ellipse(image, (300, 300), (100, 50), 0, 0, 180, (255, 0, 0), -1)
#draw polygon
pts = np.array([[10, 5], [20, 30], [70, 20], [50, 10]], np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.polylines(image, [pts], True, (0, 255, 255))

#put text
cv2.putText(image, 'OpenCV', (100, 200), font, 2, (128, 200, 40), 5,
            cv2.LINE_8)
cv2.imshow("image1", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
from cv2 import cv2
import numpy as np

# If you're wondering why only two dimensions, well this is a grayscale image,
# if we doing a colored image, we'd use
# rectangle = np.zeros((300, 300, 3), np.uint8)

# Making a square
square = np.zeros((300, 300), np.uint8)
cv2.rectangle(square, (50, 50), (250, 250), 255, -2)
cv2.imshow("Square", square)
cv2.waitKey()

# Making a ellipse
ellipse = np.zeros((300, 300), np.uint8)
cv2.ellipse(ellipse, (150, 150), (150, 150), 30, 0, 180, 255, -1)
cv2.imshow("Ellipse", ellipse)
cv2.waitKey()

cv2.destroyAllWindows()

# Shows only were they intersect
And = cv2.bitwise_and(square, ellipse)
cv2.imshow("AND", And)
cv2.waitKey()

# Shows where either square or ellipse is
bitwiseOr = cv2.bitwise_or(square, ellipse)
cv2.imshow("OR", bitwiseOr)

# Shows where either exist by itself
Пример #26
0
    #将图片输入到caffe神经网络中
    net.setInput(inp)
    #输出前向传播的预测结果
    out = net.forward()

    points = []
    for i in range(len(BODY_PARTS)):
        heatMap = out[0, i, :, :]
        _, conf, _, point = cv.minMaxLoc(heatMap)
        x = (frameWidth * point[0]) / out.shape[3]
        y = (frameHeight * point[1]) / out.shape[2]
        points.append((int(x), int(y)) if conf > 0.1 else None)

    for pair in POSE_PAIRS:
        partFrom = pair[0]
        partTo = pair[1]
        assert (partFrom in BODY_PARTS)
        assert (partTo in BODY_PARTS)

        idFrom = BODY_PARTS[partFrom]
        idTo = BODY_PARTS[partTo]

        if points[idFrom] and points[idTo]:
            cv.line(frame, points[idFrom], points[idTo], (0, 255, 0), 3)
            cv.ellipse(frame, points[idFrom], (3, 3), 0, 0, 360, (0, 0, 255),
                       cv.FILLED)
            cv.ellipse(frame, points[idTo], (3, 3), 0, 0, 360, (0, 0, 255),
                       cv.FILLED)

    cv.imshow('GuYuPose', frame)
Пример #27
0
        continue

    if radius == 0:
        continue

    #面积过滤
    areaex = np.pi * a * b
    area = cv2.contourArea(cnt)

    ratio = area / areaex

    if ratio < thresh_upper and ratio > thresh_lower:
        cntsex.append(cnt)

    show = cv2.drawContours(show, [cnt], 0, (0, 255, 0), 1)
    show = cv2.ellipse(show, center, (int(a), int(b)), 0, 0, 360, (0, 0, 255),
                       1)

#第二次过滤
cnts = []
maxarea = -1e6

for cnt in cntsex:
    area = cv2.contourArea(cnt)

    if area > maxarea:
        maxarea = area

maxgap = 0.5 * maxarea

cntsex = sorted(cntsex, key=lambda x: cv2.contourArea(x), reverse=True)
Пример #28
0
import numpy as np
from cv2 import cv2

# Create a black image
img = np.zeros((512,512,3), np.uint8)

img = cv2.line(img,(0,0),(511,511),(0,0,255),1,cv2.LINE_AA)

img = cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)

img = cv2.circle(img,(447,63), 63, (0,0,255), -1)

img = cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)

pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
pts = pts.reshape((-1,1,2))
img = cv2.polylines(img,[pts],True,(0,255,255))

font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)

# using cv show
cv2.imshow('hello', img)
# hold window
cv2.waitKey(0)
cv2.destroyAllWindows()
Пример #29
0
def circle_line(origin, thresed, S_thre=(100000, 600000)):
    # imgray = cv2.Canny(img, 300, 120, 3)
    # ret, thresh = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY)
    # cv2.imshow("thres", thresh)
    # image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # _, contours, _ = cv2.findContours(thresed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    contours, _ = cv2.findContours(thresed, cv2.RETR_TREE,
                                   cv2.CHAIN_APPROX_SIMPLE)
    top = []
    bottle = []
    right = []
    left = []
    center = []
    Circle_2D = []
    last_longest = 4
    des_ell = tuple()
    for cnt in contours:
        if len(cnt) > last_longest:  # 确保输出点数最多(且面积不超标)的椭圆
            ell = cv2.fitEllipse(
                cnt)  # 返回椭圆所在的矩形框# 函数返回值为:椭圆的中心坐标,长短轴长度(2a,2b),旋转角度
            S2 = math.pi * ell[1][0] * ell[1][1]  # 椭圆面积
            if S2 >= S_thre[0] and S2 <= S_thre[1]:  # 过滤面积小的
                last_longest = len(cnt)
                des_ell = ell

                top_x = ell[0][0] - 0.5 * ell[1][0] * math.cos(
                    math.radians(ell[2]))
                top_y = ell[0][1] - 0.5 * ell[1][0] * math.sin(
                    math.radians(ell[2]))
                bottle_x = ell[0][0] + 0.5 * ell[1][0] * math.cos(
                    math.radians(ell[2]))
                bottle_y = ell[0][1] + 0.5 * ell[1][0] * math.sin(
                    math.radians(ell[2]))

                right_x = ell[0][0] + 0.5 * ell[1][1] * math.sin(
                    math.radians(ell[2]))
                right_y = ell[0][1] - 0.5 * ell[1][1] * math.cos(
                    math.radians(ell[2]))
                left_x = ell[0][0] - 0.5 * ell[1][1] * math.sin(
                    math.radians(ell[2]))
                left_y = ell[0][1] + 0.5 * ell[1][1] * math.cos(
                    math.radians(ell[2]))

                top = (int(top_x), int(top_y))
                bottle = (int(bottle_x), int(bottle_y))
                right = (int(right_x), int(right_y))
                left = (int(left_x), int(left_y))
                center = (int(ell[0][0]), int(ell[0][1]))

    origin = cv2.ellipse(origin, des_ell, (0, 255, 0), 2)  # 绘制椭圆

    drawpoi(origin, top)
    drawpoi(origin, bottle)
    drawpoi(origin, right)
    drawpoi(origin, left)
    drawpoi(origin, center)

    # rate = ell[1][1]/ell[1][0]
    # elif S2< S_thre[1]:
    #     print("\033[0;31m椭圆面积过小!\033[0m")
    # elif S2 > S_thre[0]:
    #     print("\033[0;31m椭圆面积过大!\033[0m")
    # else:
    #     print("\033[0;31m未检测到圆桌!\033[0m")
    #     top = [0, 0]; bottle = [0, 0]; right = [0, 0]; left = [0, 0]; center = [0, 0]

    Circle_2D.append(top)
    Circle_2D.append(bottle)
    Circle_2D.append(right)
    Circle_2D.append(left)
    Circle_2D = np.array(Circle_2D, dtype='float32')
    return origin, thresed, Circle_2D