Python cv2.morphologyEx() Examples

The following are 30 code examples of cv2.morphologyEx(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: plate_locate.py    From EasyPR-python with Apache License 2.0 8 votes vote down vote up
def sobelOperT(self, img, blursize, morphW, morphH):
        '''
            No different with sobelOper ? 
        '''
        blur = cv2.GaussianBlur(img, (blursize, blursize), 0, 0, cv2.BORDER_DEFAULT)

        if len(blur.shape) == 3:
            gray = cv2.cvtColor(blur, cv2.COLOR_RGB2GRAY)
        else:
            gray = blur

        x = cv2.Sobel(gray, cv2.CV_16S, 1, 0, 3)
        absX = cv2.convertScaleAbs(x)
        grad = cv2.addWeighted(absX, 1, 0, 0, 0)

        _, threshold = cv2.threshold(grad, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)

        element = cv2.getStructuringElement(cv2.MORPH_RECT, (morphW, morphH))
        threshold = cv2.morphologyEx(threshold, cv2.MORPH_CLOSE, element)

        return threshold 
Example #2
Source File: vnet3d_train_predict.py    From LiTS---Liver-Tumor-Segmentation-Challenge with MIT License 7 votes vote down vote up
def predict0():
    Vnet3d = Vnet3dModule(256, 256, 64, inference=True, model_path="model\\Vnet3dModule.pd")
    for filenumber in range(30):
        batch_xs = np.zeros(shape=(64, 256, 256))
        for index in range(64):
            imgs = cv2.imread(
                "D:\Data\PROMISE2012\Vnet3d_data\\test\image\\" + str(filenumber) + "\\" + str(index) + ".bmp", 0)
            batch_xs[index, :, :] = imgs[128:384, 128:384]

        predictvalue = Vnet3d.prediction(batch_xs)

        for index in range(64):
            result = np.zeros(shape=(512, 512), dtype=np.uint8)
            result[128:384, 128:384] = predictvalue[index]
            kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
            result = cv2.morphologyEx(result, cv2.MORPH_CLOSE, kernel)
            cv2.imwrite(
                "D:\Data\PROMISE2012\Vnet3d_data\\test\image\\" + str(filenumber) + "\\" + str(index) + "mask.bmp",
                result) 
Example #3
Source File: Preprocess.py    From ALPR-Indonesia with MIT License 7 votes vote down vote up
def maximizeContrast(imgGrayscale):

    height, width = imgGrayscale.shape

    imgTopHat = np.zeros((height, width, 1), np.uint8)
    imgBlackHat = np.zeros((height, width, 1), np.uint8)

    structuringElement = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))

    imgTopHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_TOPHAT, structuringElement)
    imgBlackHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_BLACKHAT, structuringElement)

    imgGrayscalePlusTopHat = cv2.add(imgGrayscale, imgTopHat)
    imgGrayscalePlusTopHatMinusBlackHat = cv2.subtract(imgGrayscalePlusTopHat, imgBlackHat)

    return imgGrayscalePlusTopHatMinusBlackHat
# end function 
Example #4
Source File: getBlobTrajectories.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def getBlobContours(ROI_image, 
                    thresh, 
                    strel_size=(5, 5), 
                    is_light_background=True, 
                    analysis_type="WORM", 
                    thresh_block_size=15):

    
    ROI_image = _remove_corner_blobs(ROI_image)
    ROI_mask, thresh = _get_blob_mask(ROI_image, thresh, thresh_block_size, is_light_background, analysis_type)
    
    # clean it using morphological closing - make this optional by setting strel_size to 0
    if np.all(strel_size):
        strel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, strel_size)
        ROI_mask = cv2.morphologyEx(ROI_mask, cv2.MORPH_CLOSE, strel)

    # get worms, assuming each contour in the ROI is a worm

    ROI_worms, hierarchy = cv2.findContours(ROI_mask, 
                                               cv2.RETR_EXTERNAL, 
                                               cv2.CHAIN_APPROX_NONE)[-2:]


    return ROI_worms, hierarchy 
Example #5
Source File: getBlobTrajectories.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def getBlobsSimple(in_data, blob_params):
    frame_number, image = in_data
    min_area, worm_bw_thresh_factor, strel_size = blob_params
    
    
    img_m = cv2.medianBlur(image, 3)
    
    valid_pix = img_m[img_m>0]
    if len(valid_pix) == 0:
        return []
    
    th = _thresh_bw(valid_pix)*worm_bw_thresh_factor
    
    _, bw = cv2.threshold(img_m, th,255,cv2.THRESH_BINARY)
    if np.all(strel_size):
        strel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, strel_size)
        bw = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, strel)

    cnts, hierarchy = cv2.findContours(bw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]
    
    
    blobs_data = _cnt_to_props(cnts, frame_number, th, min_area)
    return blobs_data 
Example #6
Source File: getFoodContourMorph.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def skeletonize(img):
    """ OpenCV function to return a skeletonized version of img, a Mat object"""

    #  hat tip to http://felix.abecassis.me/2011/09/opencv-morphological-skeleton/

    img = img.copy() # don't clobber original
    skel = img.copy()

    skel[:,:] = 0
    kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3))

    while True:
        eroded = cv2.morphologyEx(img, cv2.MORPH_ERODE, kernel)
        temp = cv2.morphologyEx(eroded, cv2.MORPH_DILATE, kernel)
        temp  = cv2.subtract(img, temp)
        skel = cv2.bitwise_or(skel, temp)
        img[:,:] = eroded[:,:]
        if cv2.countNonZero(img) == 0:
            break

    return skel 
Example #7
Source File: util.py    From DeepFloorplan with GNU General Public License v3.0 6 votes vote down vote up
def fill_break_line(cw_mask):
	broken_line_h = np.array([[0,0,0,0,0],
							[0,0,0,0,0],
							[1,0,0,0,1],
							[0,0,0,0,0],
							[0,0,0,0,0]], dtype=np.uint8)	
	broken_line_h2 = np.array([[0,0,0,0,0],
							[0,0,0,0,0],
							[1,1,0,1,1],
							[0,0,0,0,0],
							[0,0,0,0,0]], dtype=np.uint8)			
	broken_line_v = np.transpose(broken_line_h)
	broken_line_v2 = np.transpose(broken_line_h2)
	cw_mask = cv2.morphologyEx(cw_mask, cv2.MORPH_CLOSE, broken_line_h)
	cw_mask = cv2.morphologyEx(cw_mask, cv2.MORPH_CLOSE, broken_line_v)
	cw_mask = cv2.morphologyEx(cw_mask, cv2.MORPH_CLOSE, broken_line_h2)
	cw_mask = cv2.morphologyEx(cw_mask, cv2.MORPH_CLOSE, broken_line_v2)

	return cw_mask 
Example #8
Source File: morphology.py    From OpenCV-Python-Tutorial with MIT License 6 votes vote down vote up
def update(dummy=None):
        sz = cv2.getTrackbarPos('op/size', 'morphology')
        iters = cv2.getTrackbarPos('iters', 'morphology')
        opers = cur_mode.split('/')
        if len(opers) > 1:
            sz = sz - 10
            op = opers[sz > 0]
            sz = abs(sz)
        else:
            op = opers[0]
        sz = sz*2+1

        str_name = 'MORPH_' + cur_str_mode.upper()
        oper_name = 'MORPH_' + op.upper()
        st = cv2.getStructuringElement(getattr(cv2, str_name), (sz, sz))
        res = cv2.morphologyEx(img, getattr(cv2, oper_name), st, iterations=iters)

        draw_str(res, (10, 20), 'mode: ' + cur_mode)
        draw_str(res, (10, 40), 'operation: ' + oper_name)
        draw_str(res, (10, 60), 'structure: ' + str_name)
        draw_str(res, (10, 80), 'ksize: %d  iters: %d' % (sz, iters))
        cv2.imshow('morphology', res) 
Example #9
Source File: plate_locate.py    From EasyPR-python with Apache License 2.0 6 votes vote down vote up
def colorSearch(self, src, color, out_rect):
        """

        :param src:
        :param color:
        :param out_rect: minAreaRect
        :return: binary
        """
        color_morph_width = 10
        color_morph_height = 2

        match_gray = colorMatch(src, color, False)

        _, src_threshold = cv2.threshold(match_gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)

        element = cv2.getStructuringElement(cv2.MORPH_RECT, (color_morph_width, color_morph_height))
        src_threshold = cv2.morphologyEx(src_threshold, cv2.MORPH_CLOSE, element)

        out = src_threshold.copy()

        _, contours, _ = cv2.findContours(src_threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

        for cnt in contours:
            mr = cv2.minAreaRect(cnt)
            if self.verifySizes(mr):
                out_rect.append(mr)

        return out 
Example #10
Source File: functions.py    From bot with MIT License 6 votes vote down vote up
def get_target_centers(img):

    # Hide buff line
    # img[0:70, 0:500] = (0, 0, 0)

    # Hide your name in first camera position (default)
    img[210:230, 350:440] = (0, 0, 0)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # cv2.imwrite('1_gray_img.png', gray)

    # Find only white text
    ret, threshold1 = cv2.threshold(gray, 252, 255, cv2.THRESH_BINARY)
    # cv2.imwrite('2_threshold1_img.png', threshold1)

    # Morphological transformation
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (50, 5))
    closed = cv2.morphologyEx(threshold1, cv2.MORPH_CLOSE, kernel)
    # cv2.imwrite('3_morphologyEx_img.png', closed)
    closed = cv2.erode(closed, kernel, iterations=1)
    # cv2.imwrite('4_erode_img.png', closed)
    closed = cv2.dilate(closed, kernel, iterations=1)
    # cv2.imwrite('5_dilate_img.png', closed)

    (_, centers, hierarchy) = cv2.findContours(closed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    return centers 
Example #11
Source File: vnet3d_train_predict.py    From VNet3D with MIT License 6 votes vote down vote up
def predict0():
    Vnet3d = Vnet3dModule(256, 256, 64, inference=True, model_path="model\\Vnet3dModule.pd")
    for filenumber in range(30):
        batch_xs = np.zeros(shape=(64, 256, 256))
        for index in range(64):
            imgs = cv2.imread(
                "D:\Data\PROMISE2012\Vnet3d_data\\test\image\\" + str(filenumber) + "\\" + str(index) + ".bmp", 0)
            batch_xs[index, :, :] = imgs[128:384, 128:384]

        predictvalue = Vnet3d.prediction(batch_xs)

        for index in range(64):
            result = np.zeros(shape=(512, 512), dtype=np.uint8)
            result[128:384, 128:384] = predictvalue[index]
            kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
            result = cv2.morphologyEx(result, cv2.MORPH_CLOSE, kernel)
            cv2.imwrite(
                "D:\Data\PROMISE2012\Vnet3d_data\\test\image\\" + str(filenumber) + "\\" + str(index) + "mask.bmp",
                result) 
Example #12
Source File: lanenet_postprocess.py    From lanenet-enet-hnet with Apache License 2.0 6 votes vote down vote up
def _morphological_process(image, kernel_size=5):
        """

        :param image:
        :param kernel_size:
        :return:
        """
        if image.dtype is not np.uint8:
            image = np.array(image, np.uint8)
        if len(image.shape) == 3:
            image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        kernel = cv2.getStructuringElement(shape=cv2.MORPH_ELLIPSE, ksize=(kernel_size, kernel_size))

        # close operation fille hole
        closing = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel, iterations=1)

        return closing 
Example #13
Source File: cvutils.py    From 1ZLAB_PyEspCar with GNU General Public License v3.0 6 votes vote down vote up
def backprojection(target, roihist):
    '''图像预处理'''
    hsvt = cv2.cvtColor(target,cv2.COLOR_BGR2HSV)
    dst = cv2.calcBackProject([hsvt],[0,1],roihist,[0,180,0,256],1)
    # Now convolute with circular disc
    disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7))
    cv2.filter2D(dst,-1,disc,dst)
    # threshold and binary AND
    ret,binary = cv2.threshold(dst,80,255,0)
    # 创建 核
    kernel = np.ones((5,5), np.uint8)
    iter_time = 1
    # 闭运算
    binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel,iterations=iter_time)

    thresh = cv2.merge((binary,binary,binary))
    target_filter = cv2.bitwise_and(target,thresh)
    
    return binary, target_filter 
Example #14
Source File: extract_yd.py    From deda with GNU General Public License v3.0 5 votes vote down vote up
def _exposeDots(self,im,ydColourRange):
        self._print(2,"Exposing dots... ")
        # method joost
        #im2 = np.array(~((np.minimum(im[:,:,2],im[:,:,1])-im[:,:,0]<20) \
        #    * (im[:,:,2]>240) * (im[:,:,1]>240)),dtype=np.uint8)*255
        
        hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
        im = cv2.inRange(hsv, *ydColourRange)
        #kernel = np.ones((6,6),np.uint8)
        #im = cv2.morphologyEx(im, cv2.MORPH_CLOSE, kernel)
        return im 
Example #15
Source File: data.py    From BraTs with MIT License 5 votes vote down vote up
def save_result(args, output):
    ''' Save Prediction results overlapping on original MRI images

    Args:
        args (argparse):    Arguments parsered in command-lind
        output (np.array):  Prediction Results by segementation model
    '''

    file_path = []
    file_path += glob.glob(os.path.join(args.image_root, args.image_folder1, '*.jpg'))
    file_path = sorted(file_path)

    output = np.argmax(output, axis=-1)*255
    kernel = np.ones((5,5),np.uint8)

    for i in range(output.shape[0]):
        save_path = os.path.join(args.output_root, str(i)+'.jpg')

        img = cv2.imread(file_path[i])
        pred = cv2.morphologyEx(output[i].astype(np.uint8), cv2.MORPH_OPEN, kernel)
        pred = cv2.morphologyEx(pred, cv2.MORPH_CLOSE, kernel)
        pred = np.expand_dims(pred, axis=2)
        zeros = np.zeros(pred.shape)
        pred = np.concatenate((zeros,zeros,pred), axis=2)
        img = img + pred
        if img.max() > 0:
            img = (img/img.max())*255
        else:
            img = (img/1)*255
        cv2.imwrite(save_path, img) 
Example #16
Source File: geometries.py    From deeposlandia with MIT License 5 votes vote down vote up
def extract_geometry_vertices(mask, structure_size=(10, 10), approx_eps=0.01):
    """Extract polygon vertices from a boolean mask with the help of OpenCV
    utilities, as a numpy array

    Parameters
    ----------
    mask : numpy.array
        Image mask where to find polygons
    structure_size : tuple
        Size of the cv2 structuring artefact, as a tuple of horizontal and
    vertical pixels
    approx_eps : double
        Approximation coefficient, aiming at building more simplified polygons
    (this coefficient lies between 0 and 1, the larger the value is, the more
    important the approximation is)

    Returns
    -------
    numpy.array
        List of polygons contained in the mask, identified by their vertices
    """
    structure = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, structure_size)
    denoised = cv2.morphologyEx(mask, cv2.MORPH_OPEN, structure)
    grown = cv2.morphologyEx(denoised, cv2.MORPH_CLOSE, structure)
    _, contours, hierarchy = cv2.findContours(
        grown, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
    )
    polygons = [
        cv2.approxPolyDP(
            c, epsilon=approx_eps * cv2.arcLength(c, closed=True), closed=True
        )
        for c in contours
    ]
    return polygons, hierarchy 
Example #17
Source File: EyeCanSee.py    From cv-lane with Apache License 2.0 5 votes vote down vote up
def filter_smooth_thres(self, RANGE, color):
        for (lower, upper) in RANGE:
            lower = np.array(lower, dtype='uint8')
            upper = np.array(upper, dtype='uint8')

            mask_bottom = cv2.inRange(self.img_roi_bottom_hsv, lower, upper)
            mask_top = cv2.inRange(self.img_roi_top_hsv, lower, upper)

        blurred_bottom = cv2.medianBlur(mask_bottom, 5)
        blurred_top = cv2.medianBlur(mask_top, 5)

        # Morphological transformation
        kernel = np.ones((2, 2), np.uint8)
        smoothen_bottom = blurred_bottom #cv2.morphologyEx(blurred, cv2.MORPH_OPEN, kernel, iterations=5)
        smoothen_top = blurred_top  # cv2.morphologyEx(blurred, cv2.MORPH_OPEN, kernel, iterations=5)

        """
        if self.debug:
            cv2.imshow('mask bottom ' + color, mask_bottom)
            cv2.imshow('blurred bottom' + color, blurred_bottom)

            cv2.imshow('mask top ' + color, mask_top)
            cv2.imshow('blurred top' + color, blurred_top)
        """

        return smoothen_bottom, smoothen_top

    # Gets metadata from our contours 
Example #18
Source File: cells.py    From SnapSudoku with MIT License 5 votes vote down vote up
def clean(self, cell):
        contour = self.helpers.largestContour(cell.copy())
        x, y, w, h = cv2.boundingRect(contour)
        cell = self.helpers.make_it_square(cell[y:y + h, x:x + w], 28)
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2))
        cell = cv2.morphologyEx(cell, cv2.MORPH_CLOSE, kernel)
        cell = 255 * (cell / 130)
        return cell 
Example #19
Source File: sudokuExtractor.py    From SnapSudoku with MIT License 5 votes vote down vote up
def preprocess(self):
        print 'Preprocessing...',
        self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
        self.image = self.helpers.thresholdify(self.image)
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2))
        self.image = cv2.morphologyEx(self.image, cv2.MORPH_CLOSE, kernel)
        print 'done.' 
Example #20
Source File: detector.py    From TextDetector with GNU General Public License v3.0 5 votes vote down vote up
def image2label(self, img, coor,
                psize, ssize, para0, para1,
                target = 'foreground'):
		''' image2label(img, coor, psize, ssize, para0, para1)

		generate label for corresponding patches
		labels are corresonding to patches get from self._image2feat
		img: 2D_numpy_array
		Return 2D_numpy_array'''
		(ind1, ind2) = map(lambda var:range(0, int(var)-psize, ssize), img.shape)
		label = numpy.zeros((len(ind1), len(ind2)))
		for bb in coor:
			# Comparing patch size:
                        if not self.width_height_comp(bb, psize, para1):
				continue
			# Comparing patch location (overlapping):
			for p, i in enumerate(ind1):
				for q, j in enumerate(ind2):
					if self.area_comp(bb, [i, j, psize, psize], para0):
						label[p, q] = 1
		if target == 'foreground':
			return label
		if target == 'whitespace':
			kernel = numpy.ones((3, 3), dtype = numpy.float32)
			labelb = cv2.dilate(label, kernel, iterations = 1) - label
			return labelb
		if target == 'whitespace_strict':
			kernel = numpy.ones((3, 1), dtype = numpy.float32)
			labelb = cv2.morphologyEx(label, cv2.MORPH_CLOSE, kernel) - label
			return labelb
                else:
                        raise Exception('Target '+target+' is not found!')
                        return 
Example #21
Source File: background.py    From Stereo-Pose-Machines with GNU General Public License v2.0 5 votes vote down vote up
def segment(self, im):
        mask = np.square(im.astype('float32') - self.bgim
                ).sum(axis=2) / 20
        mask = np.clip(mask, 0, 255).astype('uint8')
        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, self.kernel)
        mask = cv2.dilate(mask, self.dilate_k)
        mask = mask.astype('uint8')
        return (mask > 10).astype('float32') *255 
Example #22
Source File: findCard.py    From BusinessCardReader with MIT License 5 votes vote down vote up
def processCard(image_o,scale):
    #Scale image down so functions work better and turns to greyscale
    image = cv2.resize(image_o, (image_o.shape[1]/scale, image_o.shape[0]/scale))

    #Processing image to improve reliability of finding corners
    image = cv2.bilateralFilter(image, 5, 150, 50)
    imgray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

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

    imgray = cv2.morphologyEx(imgray,cv2.MORPH_OPEN,kernel)
    imgray = cv2.morphologyEx(imgray,cv2.MORPH_CLOSE,kernel)

    imgray = cv2.Canny(imgray,40,50)
    """ Ploting of image before and after processing
    plt.subplot(121)
    plt.imshow(cv2.cvtColor(image_o, cv2.COLOR_BGR2RGB))
    plt.title("Original")
    plt.axis("off")
    plt.subplot(122)
    plt.axis("off")
    plt.title("After Canny Edge")
    plt.imshow(imgray)
    plt.gray()
    plt.show()
    """

    return imgray

#Takes edited picture and find corners. Returns transformation of original image croped and transformed 
Example #23
Source File: ssocr.py    From SSOCR with GNU General Public License v3.0 5 votes vote down vote up
def preprocess(img, threshold, show=False, kernel_size=(5, 5)):
    # 直方图局部均衡化
    clahe = cv2.createCLAHE(clipLimit=2, tileGridSize=(6, 6))
    img = clahe.apply(img)
    # 自适应阈值二值化
    dst = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 127, threshold)
    # 闭运算开运算
    kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, kernel_size)
    dst = cv2.morphologyEx(dst, cv2.MORPH_CLOSE, kernel)
    dst = cv2.morphologyEx(dst, cv2.MORPH_OPEN, kernel)

    if show:
        cv2.imshow('equlizeHist', img)
        cv2.imshow('threshold', dst)
    return dst 
Example #24
Source File: imutils.py    From craves.ai with GNU General Public License v3.0 5 votes vote down vote up
def create_mask(self, img, color):
        img = cv2.cvtColor(img, cv2.COLOR_BGR2Lab)

        if color == 'green':
            threshold = [(20, 0, 128), (235, 128, 255)]
        elif color == 'white':
            threshold = [(100, 110, 110), (200, 140, 140)]

        else:
            raise Exception('Color undefined')
        
        mask = cv2.inRange(img, threshold[0], threshold[1])
        # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7,7))
        # mask =  cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
        # mask =  cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

        mask = mask > 0

        # img = cv2.cvtColor(img, cv2.COLOR_YCR_CB2BGR)

        # thres_img = np.zeros_like(img, np.uint8)
        # thres_img[mask] = img[mask]

        binary_img = np.zeros((img.shape[0],img.shape[1]), np.uint8)
        binary_img[mask] = 255

        # cv2.imshow('img', binary_img)
        # cv2.waitKey(0)
        # exit(0)

        return mask 
Example #25
Source File: MeterReader.py    From Pointer-meter-identification-and-reading with MIT License 5 votes vote down vote up
def open_operation(self,img):
        # 定义结构元素
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))  # 矩形结构
        # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))   # 椭圆结构
        # kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))     # 十字形结构
        opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)  # 开运算
        cv2.imshow('Open operation', opening)
        return opening

    # 霍夫圆变换:检测表盘 
Example #26
Source File: page_elements2.py    From namsel with MIT License 5 votes vote down vote up
def _draw_new_page(self):
        self.page_array = np.ones_like(self.img_arr)
        
        self.tall = set([i for i in self.get_indices() if 
                         self.get_boxes()[i][3] > 3*self.char_mean])
        
#        cv.drawContours(self.page_array, [self.contours[i] for i in 
#                        self.get_indices() if self.get_boxes()[i][2] <= self.tsek_mean + 3*self.tsek_std], 
#                        -1,0, thickness = -1)
#        
#        
#        self.page_array = cv.medianBlur(self.page_array, 19)
#        
#        cv.drawContours(self.page_array, [self.contours[i] for i in 
#                        self.get_indices() if self.get_boxes()[i][2] <= self.tsek_mean + 3*self.tsek_std], 
#                        -1,0, thickness = -1)
        cv.drawContours(self.page_array, [self.contours[i] for i in 
                        range(len(self.contours)) if 
                        self.get_boxes()[i][2] > self.smlmean + 3*self.smstd], 
                        -1,0, thickness = -1)
#        cv.drawContours(self.page_array, [self.contours[i] for i in 
#                        self.get_indices() if self.get_boxes()[i][3] <= 2*self.char_mean], 
#                        -1,0, thickness = -1)
#        cv.erode(self.page_array, None, self.page_array, iterations=2)
#        self.page_array = cv.morphologyEx(self.page_array, cv.MORPH_CLOSE, None,iterations=2)
        import Image
        Image.fromarray(self.page_array*255).show()
#        raw_input()
#        cv.dilate(self.page_array, None, self.page_array, iterations=1) 
Example #27
Source File: common.py    From baxter_demos with Apache License 2.0 5 votes vote down vote up
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 
Example #28
Source File: transforms.py    From ChaLearn_liveness_challenge with MIT License 5 votes vote down vote up
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 
Example #29
Source File: motion_detection.py    From pynvr with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #30
Source File: main.py    From sbb_textline_detection with Apache License 2.0 5 votes vote down vote up
def return_rotated_contours(self,slope,img_patch):
            dst = self.rotate_image(img_patch, slope)
            dst = dst.astype(np.uint8)
            dst = dst[:, :, 0]
            dst[dst != 0] = 1
            
            imgray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)
            _, thresh = cv2.threshold(imgray, 0, 255, 0)
            thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
            thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
            contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            return contours