當前位置: 首頁>>代碼示例>>Python>>正文


Python cv2.MORPH_OPEN屬性代碼示例

本文整理匯總了Python中cv2.MORPH_OPEN屬性的典型用法代碼示例。如果您正苦於以下問題:Python cv2.MORPH_OPEN屬性的具體用法?Python cv2.MORPH_OPEN怎麽用?Python cv2.MORPH_OPEN使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在cv2的用法示例。


在下文中一共展示了cv2.MORPH_OPEN屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: colorTarget

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def colorTarget(color_range=((0, 0, 0), (255, 255, 255))):

    image = cam.newImage()
    if filter == 'RGB':
        frame_to_thresh = image.copy()
    else:
        frame_to_thresh = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)                            # convert image to hsv colorspace RENAME THIS TO IMAGE_HSV

    thresh = cv2.inRange(frame_to_thresh, color_range[0], color_range[1])

    # apply a blur function
    kernel = np.ones((5, 5), np.uint8)
    mask = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)                                 # Apply blur
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)                                  # Apply blur 2nd iteration

    cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]    # generates number of contiguous "1" pixels
    if len(cnts) > 0:                                                                       # begin processing if there are "1" pixels discovered
        c = max(cnts, key=cv2.contourArea)                                                  # return the largest target area
        ((x, y), radius) = cv2.minEnclosingCircle(c)
        return np.array([round(x, 1), round(y, 1), round(radius, 1)])
    else:
        return np.array([None, None, 0]) 
開發者ID:MXET,項目名稱:SCUTTLE,代碼行數:24,代碼來源:L2_track_target.py

示例2: returnMask

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def returnMask(self, frame, morph_opening=True, blur=True, kernel_size=5, iterations=1):
        """Given an input frame return the black/white mask.
 
        This version of the function does not use the blur and bitwise 
        operations, then the resulting frame contains white pixels
        in correspondance of the skin found during the searching process.
        @param frame the original frame (color)
        """
        #Convert to HSV and eliminate pixels outside the range
        frame_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        frame_filtered = cv2.inRange(frame_hsv, self.min_range, self.max_range)
        if(morph_opening==True):
            kernel = np.ones((kernel_size,kernel_size), np.uint8)
            frame_filtered = cv2.morphologyEx(frame_filtered, cv2.MORPH_OPEN, kernel, iterations=iterations)
        #Applying Gaussian Blur
        if(blur==True): 
            frame_filtered = cv2.GaussianBlur(frame_filtered, (kernel_size,kernel_size), 0)
        return frame_filtered 
開發者ID:mpatacchiola,項目名稱:deepgaze,代碼行數:20,代碼來源:color_detection.py

示例3: motionDetected

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def motionDetected(self, new_frame):
        frame = self.preprocessInputFrame(new_frame)

        gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        gray = cv.GaussianBlur(gray, (21, 21), 0)

        if self.prevFrame is None:
            self.prevFrame = gray
            return False

        frameDiff = cv.absdiff(gray, self.prevFrame)

        # kernel = np.ones((5, 5), np.uint8)

        opening = cv.morphologyEx(frameDiff, cv.MORPH_OPEN, None)  # noqa
        closing = cv.morphologyEx(frameDiff, cv.MORPH_CLOSE, None)  # noqa

        ret1, th1 = cv.threshold(frameDiff, 10, 255, cv.THRESH_BINARY)

        height = np.size(th1, 0)
        width = np.size(th1, 1)

        nb = cv.countNonZero(th1)

        avg = (nb * 100) / (height * width)  # Calculate the average of black pixel in the image

        self.prevFrame = gray

        # cv.DrawContours(currentframe, self.currentcontours, (0, 0, 255), (0, 255, 0), 1, 2, cv.CV_FILLED)
        # cv.imshow("frame", current_frame)

        ret = avg > self.threshold   # If over the ceiling trigger the alarm

        if ret:
            self.updateMotionDetectionDts()

        return ret 
開發者ID:JFF-Bohdan,項目名稱:pynvr,代碼行數:39,代碼來源:motion_detection.py

示例4: denoise

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def denoise(mask, eps):
    """Removes noise from a mask.

    Args:
      mask: the mask to remove noise from.
      eps: the morphological operation's kernel size for noise removal, in pixel.

    Returns:
      The mask after applying denoising.
    """

    struct = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (eps, eps))
    return cv2.morphologyEx(mask, cv2.MORPH_OPEN, struct) 
開發者ID:mapbox,項目名稱:robosat,代碼行數:15,代碼來源:core.py

示例5: gradient_and_binary

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def gradient_and_binary(img_blurred, image_name='1.jpg', save_path='./'):  # 將灰度圖二值化,後麵兩個參數調試用
    """
    求取梯度,二值化
    :param img_blurred: 濾波後的圖片
    :param image_name: 圖片名,測試用
    :param save_path: 保存路徑,測試用
    :return:  二值化後的圖片
    """
    gradX = cv2.Sobel(img_blurred, ddepth=cv2.CV_32F, dx=1, dy=0)
    gradY = cv2.Sobel(img_blurred, ddepth=cv2.CV_32F, dx=0, dy=1)
    img_gradient = cv2.subtract(gradX, gradY)
    img_gradient = cv2.convertScaleAbs(img_gradient)  # sobel算子,計算梯度, 也可以用canny算子替代

    # 這裏改進成自適應閾值,貌似沒用
    img_thresh = cv2.adaptiveThreshold(img_gradient, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, -3)
    # cv2.imwrite(os.path.join(save_path, img_name + '_binary.jpg'), img_thresh)  # 二值化 閾值未調整好

    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    img_closed = cv2.morphologyEx(img_thresh, cv2.MORPH_CLOSE, kernel)
    img_closed = cv2.morphologyEx(img_closed, cv2.MORPH_OPEN, kernel)
    img_closed = cv2.erode(img_closed, None, iterations=9)
    img_closed = cv2.dilate(img_closed, None, iterations=9)  # 腐蝕膨脹
    # 這裏調整了kernel大小(減小),腐蝕膨脹次數後(增大),出錯的概率大幅減小

    return img_closed 
開發者ID:Mingtzge,項目名稱:2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement,代碼行數:27,代碼來源:cut_part.py

示例6: _filter_image

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def _filter_image(self, image):
        _, thresh = cv2.threshold(image, 200, 255, cv2.THRESH_BINARY)
        opened = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, (5, 5), iterations=3)

        return cv2.bitwise_not(opened) 
開發者ID:nemanja-m,項目名稱:gaps,代碼行數:7,代碼來源:size_detector.py

示例7: roiMask

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def roiMask(image, boundaries):
    scale = max([1.0, np.average(np.array(image.shape)[0:2] / 400.0)])
    shape = (int(round(image.shape[1] / scale)), int(round(image.shape[0] / scale)))

    small_color = cv2.resize(image, shape, interpolation=cv2.INTER_LINEAR)

    # reduce details and remove noise for better edge detection
    small_color = cv2.bilateralFilter(small_color, 8, 64, 64)
    small_color = cv2.pyrMeanShiftFiltering(small_color, 8, 64, maxLevel=1)
    small = cv2.cvtColor(small_color, cv2.COLOR_BGR2HSV)

    hue = small[::, ::, 0]
    intensity = cv2.cvtColor(small_color, cv2.COLOR_BGR2GRAY)

    edges = extractEdges(hue, intensity)
    roi = roiFromEdges(edges)
    weight_map = weightMap(hue, intensity, edges, roi)

    _, final_mask = cv2.threshold(roi, 5, 255, cv2.THRESH_BINARY)
    small = cv2.bitwise_and(small, small, mask=final_mask)

    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4))

    for (lower, upper) in boundaries:
        lower = np.array([lower, 80, 50], dtype="uint8")
        upper = np.array([upper, 255, 255], dtype="uint8")

        # find the colors within the specified boundaries and apply
        # the mask
        mask = cv2.inRange(small, lower, upper)
        mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=3)
        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
        final_mask = cv2.bitwise_and(final_mask, mask)

    # blur the mask for better contour extraction
    final_mask = cv2.GaussianBlur(final_mask, (5, 5), 0)
    return (final_mask, weight_map, scale) 
開發者ID:AVGInnovationLabs,項目名稱:DoNotSnap,代碼行數:39,代碼來源:RegionOfInterest.py

示例8: morph_postprocess

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def morph_postprocess(img):
    kernel = np.ones((5,5),np.uint8)
    
    # --- opening ---
    img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)

    # --- closing ---
    img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
    return img 
開發者ID:saeedizadi,項目名稱:binseg_pytoch,代碼行數:11,代碼來源:tools.py

示例9: morph_process

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def morph_process(image):
    """
    圖像形態學變化
    :param image:
    :return:
    """
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    close_image = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel)
    open_image = cv2.morphologyEx(close_image, cv2.MORPH_OPEN, kernel)

    return open_image 
開發者ID:MaybeShewill-CV,項目名稱:attentive-gan-derainnet,代碼行數:13,代碼來源:tf_io_pipline_tools.py

示例10: segment

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def segment(self, image):
        mask = np.array(image[:, :, 1] < self._threshold).astype(np.uint8)
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
        mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
        return mask * 255 
開發者ID:cytomine,項目名稱:Cytomine-python-datamining,代碼行數:8,代碼來源:add_and_run_job.py

示例11: morphological_transformations

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def morphological_transformations(im_thresh, morpho_type="CLOSE", kernel_shape=(5, 5), kernel_type="ELLIPSE"):
    """
    Take black & white image and apply morphological transformation
    :param im_thresh: Black & White Image
    :param morpho_type: CLOSE/OPEN/ERODE/DILATE => See on OpenCV/Google if you do not know these words
    :param kernel_shape: tuple corresponding to the size of the kernel
    :param kernel_type: RECT/ELLIPSE/CROSS => see on OpenCV
    :return: image after processing
    """
    if kernel_type == "CROSS":
        kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, kernel_shape)
    elif kernel_type == "RECT":
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, kernel_shape)
    else:
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, kernel_shape)

    if morpho_type == "OPEN":
        morph_type = cv2.MORPH_OPEN
    elif morpho_type == "DILATE":
        morph_type = cv2.MORPH_DILATE
    elif morpho_type == "ERODE":
        morph_type = cv2.MORPH_ERODE
    else:
        morph_type = cv2.MORPH_CLOSE

    return cv2.morphologyEx(im_thresh, morph_type, kernel)


# Contours 
開發者ID:NiryoRobotics,項目名稱:niryo_one_ros,代碼行數:31,代碼來源:image_functions.py

示例12: removeBG

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def removeBG(frame):
    fgmask = bgModel.apply(frame,learningRate=learningRate)
    # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
    # res = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)

    kernel = np.ones((3, 3), np.uint8)
    fgmask = cv2.erode(fgmask, kernel, iterations=1)
    res = cv2.bitwise_and(frame, frame, mask=fgmask)
    return res 
開發者ID:lzane,項目名稱:Fingers-Detection-using-OpenCV-and-Python,代碼行數:11,代碼來源:new.py

示例13: reduce_noise_edges

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def reduce_noise_edges(im):
    structuring_element = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 1))
    opening = cv2.morphologyEx(im, cv2.MORPH_OPEN, structuring_element)
    maxed_rows = rank_filter(opening, -4, size=(1, 20))
    maxed_cols = rank_filter(opening, -4, size=(20, 1))
    debordered = np.minimum(np.minimum(opening, maxed_rows), maxed_cols)
    return debordered 
開發者ID:jlsutherland,項目名稱:doc2text,代碼行數:9,代碼來源:page.py

示例14: __call__

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def __call__(self, img_dict):
        data_get_func = img_dict['meta']['get_item_func']
        curr_idx = img_dict['meta']['idx']
        max_idx = img_dict['meta']['max_idx']
        
        other_idx = np.random.randint(0, max_idx)
        data4augm = data_get_func(other_idx)
        while (curr_idx == other_idx) or (self.same_label and data4augm['label'] != img_dict['label']):
            other_idx = np.random.randint(0, max_idx)
            data4augm = data_get_func(other_idx)
            
        depth4augm = data4augm['depth'].resize(img_dict['depth'].size)
        mask4augm = np.array(depth4augm.convert('L')) > 0
        mask4augm = cv2.morphologyEx(mask4augm.astype(np.uint8), 
                                     cv2.MORPH_OPEN, 
                                     self.kernel_orgl)
        
        mask = np.array(img_dict['depth'].convert('L')) > 0
        mask = cv2.morphologyEx(mask.astype(np.uint8), 
                                cv2.MORPH_OPEN, 
                                self.kernel_augm)
        mask = (mask == mask4augm) & (mask)
        mask = np.repeat(np.expand_dims(mask, 2), 3, axis=2)
        
        keys = ['depth', 'ir']
        for key in keys:
            np_img = np.array(img_dict[key]) * mask
            img_dict[key] = Image.fromarray(np_img)
        return img_dict 
開發者ID:AlexanderParkin,項目名稱:ChaLearn_liveness_challenge,代碼行數:31,代碼來源:transforms.py

示例15: colorSegmentation

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import MORPH_OPEN [as 別名]
def colorSegmentation(img, blur_radius, radius, open_radius, color):

    #Get color of point in image
    #print self.point
    #Grab the R, G, B channels as separate matrices
    #use cv2.threshold on each of them
    #AND the three images together
    bw = numpy.ones(img.shape[0:2], numpy.uint8)
    maxvals = [179, 255, 255]
    for i in range(3):
        minval = color[i] - radius
        maxval = color[i] + radius
        if radius > color[i]:
            minval = 0
        elif radius + color[i] > maxvals[i]:
            minval = color[i] - radius

        channel = img[:, :, i]
        retval, minthresh = cv2.threshold(channel, minval, 255, cv2.THRESH_BINARY)
        retval, maxthresh = cv2.threshold(channel, maxval, 255, cv2.THRESH_BINARY_INV)
        bw = cv2.bitwise_and(bw, minthresh)
        bw = cv2.bitwise_and(bw, maxthresh)
    bw *= 255
    
    if open_radius != 0:
        open_kernel = numpy.array([open_radius, open_radius])

        bw = cv2.morphologyEx(bw, cv2.MORPH_OPEN, open_kernel, iterations = 4)

    return bw 
開發者ID:osrf,項目名稱:baxter_demos,代碼行數:32,代碼來源:common.py


注:本文中的cv2.MORPH_OPEN屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。