Python cv2.THRESH_BINARY Examples

The following are 30 code examples for showing how to use cv2.THRESH_BINARY(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module cv2 , or try the search function .

Example 1
Project: vrequest   Author: cilame   File: pycv2.py    License: MIT License 17 votes vote down vote up
def laplacian(filepathname):
    v = cv2.imread(filepathname)
    s = cv2.cvtColor(v, cv2.COLOR_BGR2GRAY)
    s = cv2.Laplacian(s, cv2.CV_16S, ksize=3)
    s = cv2.convertScaleAbs(s)
    cv2.imshow('nier',s)
    return s

    # ret, binary = cv2.threshold(s,40,255,cv2.THRESH_BINARY)
    # contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    # for c in contours:
    #     x,y,w,h = cv2.boundingRect(c)
    #     if w>5 and h>10:
    #         cv2.rectangle(v,(x,y),(x+w,y+h),(155,155,0),1)
    # cv2.imshow('nier2',v)

    # cv2.waitKey()
    # cv2.destroyAllWindows() 
Example 2
Project: gesture-recognition   Author: Gogul09   File: segment.py    License: MIT License 12 votes vote down vote up
def segment(image, threshold=25):
    global bg
    # find the absolute difference between background and current frame
    diff = cv2.absdiff(bg.astype("uint8"), image)

    # threshold the diff image so that we get the foreground
    thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]

    # get the contours in the thresholded image
    (_, cnts, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # return None, if no contours detected
    if len(cnts) == 0:
        return
    else:
        # based on contour area, get the maximum contour which is the hand
        segmented = max(cnts, key=cv2.contourArea)
        return (thresholded, segmented)

#-----------------
# MAIN FUNCTION
#----------------- 
Example 3
Project: object-detection   Author: cristianpb   File: motion.py    License: MIT License 10 votes vote down vote up
def prediction(self, image):
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        image = cv2.GaussianBlur(image, (21, 21), 0)
        if self.avg is None:
            self.avg = image.copy().astype(float)
        cv2.accumulateWeighted(image, self.avg, 0.5)
        frameDelta = cv2.absdiff(image, cv2.convertScaleAbs(self.avg))
        thresh = cv2.threshold(
                frameDelta, DELTA_THRESH, 255,
                cv2.THRESH_BINARY)[1]
        thresh = cv2.dilate(thresh, None, iterations=2)
        cnts = cv2.findContours(
                thresh.copy(), cv2.RETR_EXTERNAL,
                cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)
        self.avg = image.copy().astype(float)
        return cnts 
Example 4
Project: vrequest   Author: cilame   File: pycv2.py    License: MIT License 8 votes vote down vote up
def canny(filepathname, left=70, right=140):
    v = cv2.imread(filepathname)
    s = cv2.cvtColor(v, cv2.COLOR_BGR2GRAY)
    s = cv2.Canny(s, left, right)
    cv2.imshow('nier',s)
    return s

    # 圈出最小方矩形框,这里Canny算法后都是白色线条,所以取色范围 127-255 即可。
    # ret, binary = cv2.threshold(s,127,255,cv2.THRESH_BINARY) 
    # contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    # for c in contours:
    #     x,y,w,h = cv2.boundingRect(c)
    #     if w>5 and h>10: # 有约束的画框
    #         cv2.rectangle(v,(x,y),(x+w,y+h),(155,155,0),1)
    # # cv2.drawContours(s,contours,-1,(0,0,255),3) # 画所有框
    # cv2.imshow('nier2',v)

    # cv2.waitKey()
    # cv2.destroyAllWindows() 
Example 5
Project: OpenCV-Python-Tutorial   Author: makelove   File: squares.py    License: MIT License 7 votes vote down vote up
def find_squares(img):
    img = cv2.GaussianBlur(img, (5, 5), 0)
    squares = []
    for gray in cv2.split(img):
        for thrs in xrange(0, 255, 26):
            if thrs == 0:
                bin = cv2.Canny(gray, 0, 50, apertureSize=5)
                bin = cv2.dilate(bin, None)
            else:
                retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
            bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
            for cnt in contours:
                cnt_len = cv2.arcLength(cnt, True)
                cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
                if len(cnt) == 4 and cv2.contourArea(cnt) > 1000 and cv2.isContourConvex(cnt):
                    cnt = cnt.reshape(-1, 2)
                    max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
                    if max_cos < 0.1:
                        squares.append(cnt)
    return squares 
Example 6
Project: crop_row_detection   Author: petern3   File: camera_test.py    License: GNU General Public License v3.0 7 votes vote down vote up
def main():
	capture = cv2.VideoCapture(0)
	_, image = capture.read()
	previous = image.copy()
	
	
	while (cv2.waitKey(1) < 0):
		_, image = capture.read()
		diff = cv2.absdiff(image, previous)
		#image = cv2.flip(image, 3)
		#image = cv2.norm(image)
		_, diff = cv2.threshold(diff, 32, 0, cv2.THRESH_TOZERO)
		_, diff = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY)
		
		diff = cv2.medianBlur(diff, 5)
		
		cv2.imshow('video', diff)
		previous = image.copy()
		
	capture.release()
	cv2.destroyAllWindows() 
Example 7
Project: crop_row_detection   Author: petern3   File: line_detect_2.py    License: GNU General Public License v3.0 7 votes vote down vote up
def skeletonize(image_in):
    '''Inputs and grayscale image and outputs a binary skeleton image'''
    size = np.size(image_in)
    skel = np.zeros(image_in.shape, np.uint8)

    ret, image_edit = cv2.threshold(image_in, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3))
    done = False

    while not done:
        eroded = cv2.erode(image_edit, element)
        temp = cv2.dilate(eroded, element)
        temp = cv2.subtract(image_edit, temp)
        skel = cv2.bitwise_or(skel, temp)
        image_edit = eroded.copy()

        zeros = size - cv2.countNonZero(image_edit)
        if zeros == size:
            done = True

    return skel 
Example 8
Project: OpenCV-Computer-Vision-Projects-with-Python   Author: PacktPublishing   File: saliency.py    License: MIT License 6 votes vote down vote up
def get_proto_objects_map(self, use_otsu=True):
        """Returns the proto-objects map of an RGB image

            This method generates a proto-objects map of an RGB image.
            Proto-objects are saliency hot spots, generated by thresholding
            the saliency map.

            :param use_otsu: flag whether to use Otsu thresholding (True) or
                             a hardcoded threshold value (False)
            :returns: proto-objects map
        """
        saliency = self.get_saliency_map()

        if use_otsu:
            _, img_objects = cv2.threshold(np.uint8(saliency*255), 0, 255,
                                           cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        else:
            thresh = np.mean(saliency)*255*3
            _, img_objects = cv2.threshold(np.uint8(saliency*255), thresh, 255,
                                           cv2.THRESH_BINARY)
        return img_objects 
Example 9
Project: crop_row_detection   Author: petern3   File: line_detect_1.py    License: GNU General Public License v3.0 6 votes vote down vote up
def crop_row_detect(image_in):
    
    save_image('0_image_in', image_in)
    
    ### Grayscale Transform ###
    image_edit = grayscale_transform(image_in)
    save_image('1_image_gray', image_edit)
        
    ### Binarization ###
    _, image_edit = cv2.threshold(image_edit, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    save_image('2_image_bin', image_edit)
    
    ### Stripping ###
    crop_points = strip_process(image_edit)
    save_image('8_crop_points', crop_points)
    
    ### Hough Transform ###
    crop_lines = crop_point_hough(crop_points)
    save_image('9_image_hough', cv2.addWeighted(image_in, 1, crop_lines, 1, 0.0))
    
    return crop_lines 
Example 10
Project: hazymaze   Author: guille0   File: helpers.py    License: Apache License 2.0 6 votes vote down vote up
def blend_non_transparent(sprite, background_img):
    gray_overlay = cv2.cvtColor(background_img, cv2.COLOR_BGR2GRAY)
    overlay_mask = cv2.threshold(gray_overlay, 1, 255, cv2.THRESH_BINARY)[1]

    overlay_mask = cv2.erode(overlay_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
    overlay_mask = cv2.blur(overlay_mask, (3, 3))

    background_mask = 255 - overlay_mask

    overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR)
    background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR)

    sprite_part = (sprite * (1 / 255.0)) * (background_mask * (1 / 255.0))
    overlay_part = (background_img * (1 / 255.0)) * (overlay_mask * (1 / 255.0))

    return np.uint8(cv2.addWeighted(sprite_part, 255.0, overlay_part, 255.0, 0.0)) 
Example 11
Project: SolveSudoku   Author: aakashjhawar   File: SudokuExtractor.py    License: MIT License 6 votes vote down vote up
def pre_process_image(img, skip_dilate=False):
	"""Uses a blurring function, adaptive thresholding and dilation to expose the main features of an image."""

	# Gaussian blur with a kernal size (height, width) of 9.
	# Note that kernal sizes must be positive and odd and the kernel must be square.
	proc = cv2.GaussianBlur(img.copy(), (9, 9), 0)

	# Adaptive threshold using 11 nearest neighbour pixels
	proc = cv2.adaptiveThreshold(proc, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

	# Invert colours, so gridlines have non-zero pixel values.
	# Necessary to dilate the image, otherwise will look like erosion instead.
	proc = cv2.bitwise_not(proc, proc)

	if not skip_dilate:
		# Dilate the image to increase the size of the grid lines.
		kernel = np.array([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]],np.uint8)
		proc = cv2.dilate(proc, kernel)

	return proc 
Example 12
Project: EasyPR-python   Author: SunskyF   File: plate_locate.py    License: Apache License 2.0 6 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 13
Project: EasyPR-python   Author: SunskyF   File: plate_locate.py    License: Apache License 2.0 6 votes vote down vote up
def DeleteNotArea(self, in_img):
        input_gray = cv2.cvtColor(in_img, cv2.COLOR_BGR2GRAY)
        w = in_img.shape[1]
        h = in_img.shape[0]
        tmp_mat = in_img[int(h * 0.1):int(h * 0.85), int(w * 0.15):int(w * 0.85)]

        plateType = getPlateType(tmp_mat, True)

        if plateType == 'BLUE':
            tmp = in_img[int(h * 0.1):int(h * 0.85), int(w * 0.15):int(w * 0.85)]
            threadHoldV = ThresholdOtsu(tmp)
            _, img_threshold = cv2.threshold(input_gray, threadHoldV, 255, cv2.THRESH_BINARY)
        elif plateType == 'YELLOW':
            tmp = in_img[int(h * 0.1):int(h * 0.85), int(w * 0.15):int(w * 0.85)]
            threadHoldV = ThresholdOtsu(tmp)
            _, img_threshold = cv2.threshold(input_gray, threadHoldV, 255, cv2.THRESH_BINARY_INV)
        else:
            _, img_threshold = cv2.threshold(input_gray, 10, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)

        top, bottom = clearLiuDing(img_threshold, 0, img_threshold.shape[0] - 1)
        posLeft, posRight, flag = bFindLeftRightBound1(img_threshold)

        if flag:
            in_img = in_img[int(top):int(bottom), int(posLeft):int(w)] 
Example 14
Project: EasyPR-python   Author: SunskyF   File: plate_locate.py    License: 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 15
Project: vrequest   Author: cilame   File: pycv2.py    License: MIT License 6 votes vote down vote up
def sobel(filepathname):
    v = cv2.imread(filepathname)
    s = cv2.cvtColor(v,cv2.COLOR_BGR2GRAY)
    x, y = cv2.Sobel(s,cv2.CV_16S,1,0), cv2.Sobel(s,cv2.CV_16S,0,1)
    s = cv2.convertScaleAbs(cv2.subtract(x,y))
    s = cv2.blur(s,(9,9))
    cv2.imshow('nier',s)
    return s

    # ret, binary = cv2.threshold(s,40,255,cv2.THRESH_BINARY)
    # contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    # for c in contours:
    #     x,y,w,h = cv2.boundingRect(c)
    #     if w>5 and h>10:
    #         cv2.rectangle(v,(x,y),(x+w,y+h),(155,155,0),1)
    # cv2.imshow('nier2',v)

    # cv2.waitKey()
    # cv2.destroyAllWindows() 
Example 16
Project: gesture-recognition   Author: Gogul09   File: recognize.py    License: MIT License 6 votes vote down vote up
def segment(image, threshold=25):
    global bg
    # find the absolute difference between background and current frame
    diff = cv2.absdiff(bg.astype("uint8"), image)

    # threshold the diff image so that we get the foreground
    thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]

    # get the contours in the thresholded image
    (_, cnts, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # return None, if no contours detected
    if len(cnts) == 0:
        return
    else:
        # based on contour area, get the maximum contour which is the hand
        segmented = max(cnts, key=cv2.contourArea)
        return (thresholded, segmented)

#--------------------------------------------------------------
# To count the number of fingers in the segmented hand region
#-------------------------------------------------------------- 
Example 17
Project: smashscan   Author: jpnaterer   File: util.py    License: MIT License 6 votes vote down vote up
def get_image_and_mask(img_location, gray_flag):

    # Load image from file with alpha channel (UNCHANGED flag). If an alpha
    # channel does not exist, just return the base image.
    img = cv2.imread(img_location, cv2.IMREAD_UNCHANGED)
    if img.shape[2] <= 3:
        return img, None

    # Create an alpha channel matrix  with values between 0-255. Then
    # threshold the alpha channel to create a binary mask.
    channels = cv2.split(img)
    mask = np.array(channels[3])
    _, mask = cv2.threshold(mask, 250, 255, cv2.THRESH_BINARY)

    # Convert image and mask to grayscale or BGR based on input flag.
    if gray_flag:
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
    else:
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
        mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)

    return img, mask


# Resize an image and mask based on an input scale ratio. 
Example 18
Project: smashscan   Author: jpnaterer   File: thresholding.py    License: MIT License 6 votes vote down vote up
def param_filter(self, frame):
        # Apply pre-blur according to trackbar value.
        if self.pre_blur_val == 1:
            frame = cv2.GaussianBlur(frame, (5, 5), 0)
        elif self.pre_blur_val == 2:
            frame = cv2.medianBlur(frame, 5)

        # Apply a thresholding method according to trackbar value.
        if self.thresh_flag:
            _, frame = cv2.threshold(frame, 127, 255, cv2.THRESH_BINARY)
        else:
            _, frame = cv2.threshold(frame, 127, 255, cv2.THRESH_OTSU)

        # Apply post-blur according to trackbar value.
        if self.post_blur_val:
            frame = cv2.medianBlur(frame, 5)

        return frame


    # Apply filterrs to frame according to contour parameters. 
Example 19
Project: IkaLog   Author: hasegaw   File: result_detail.py    License: Apache License 2.0 6 votes vote down vote up
def is_entry_me(self, img_entry):
        # ヒストグラムから、入力エントリが自分かを判断
        if len(img_entry.shape) > 2 and img_entry.shape[2] != 1:
            img_me = cv2.cvtColor(img_entry[:, 0:43], cv2.COLOR_BGR2GRAY)
        else:
            img_me = img_entry[:, 0:43]

        img_me = cv2.threshold(img_me, 230, 255, cv2.THRESH_BINARY)[1]

        me_score = np.sum(img_me)
        me_score_normalized = 0
        try:
            me_score_normalized = me_score / (43 * 45 * 255 / 10)
        except ZeroDivisionError as e:
            me_score_normalized = 0

        #print("score=%3.3f" % me_score_normalized)

        return (me_score_normalized > 1) 
Example 20
Project: pynvr   Author: JFF-Bohdan   File: motion_detection.py    License: 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 21
Project: pynvr   Author: JFF-Bohdan   File: motion_detection.py    License: 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, (11, 11), 0)

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

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

        cv.normalize(gray, gray, 0, 255, cv.NORM_MINMAX)

        frameDiff = self.diffImg(self.prevPrevFrame, self.prevFrame, gray)
        ret1, th1 = cv.threshold(frameDiff, 10, 255, cv.THRESH_BINARY)

        cv.dilate(th1, None, iterations=15)
        cv.erode(th1, None, iterations=1)

        delta_count = cv.countNonZero(th1)

        cv.imshow("frame_th1", th1)

        self.prevPrevFrame = self.prevFrame
        self.prevFrame = gray

        ret = delta_count > self.threshold

        if ret:
            self.updateMotionDetectionDts()

        return ret 
Example 22
Project: pynvr   Author: JFF-Bohdan   File: motion_detection.py    License: 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, (11, 11), 0)

        if (self.multiFrameDetection) and (self.prevPrevFrame is None):
            self.prevPrevFrame = gray
            return False

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

        cv.normalize(gray, gray, 0, 255, cv.NORM_MINMAX)

        frameDiff = self.diffImg(self.prevPrevFrame, self.prevFrame, gray)
        ret1, th1 = cv.threshold(frameDiff, 10, 255, cv.THRESH_BINARY)

        th1 = cv.dilate(th1, None, iterations=8)
        th1 = cv.erode(th1, None, iterations=4)

        delta_count = cv.countNonZero(th1)

        if self.multiFrameDetection:
            self.prevPrevFrame = self.prevFrame

        self.prevFrame = gray
        if delta_count < self.threshold:
            return False

        if self.multiFrameDetection:
            self.prevPrevFrame = self.prevFrame

        self.prevFrame = gray
        self.updateMotionDetectionDts()
        return True 
Example 23
Project: display_ocr   Author: arturaugusto   File: digital_display_ocr.py    License: GNU General Public License v2.0 5 votes vote down vote up
def process_image(orig_image_arr):
  ratio = orig_image_arr.shape[0] / 300.0

  display_image_arr = normalize_contrs(orig_image_arr,crop_display(orig_image_arr))
  #display image is now segmented.
  gry_disp_arr = cv2.cvtColor(display_image_arr, cv2.COLOR_BGR2GRAY)
  gry_disp_arr = exposure.rescale_intensity(gry_disp_arr, out_range= (0,255))

  #thresholding
  ret, thresh = cv2.threshold(gry_disp_arr,127,255,cv2.THRESH_BINARY)
  return thresh 
Example 24
Project: OpenCV-Computer-Vision-Projects-with-Python   Author: PacktPublishing   File: chapter2.py    License: MIT License 5 votes vote down vote up
def SegmentArm(self, frame):
        """ segments the arm region based on depth """
        # find center (21x21 pixel) region of image frame
        centerHalf = 10 # half-width of 21 is 21/2-1
        center = frame[self.imgHeight/2-centerHalf:self.imgHeight/2+centerHalf,
            self.imgWidth/2-centerHalf:self.imgWidth/2+centerHalf]

        # find median depth value of center region
        center = np.reshape(center, np.prod(center.shape))
        medVal = np.median( np.reshape(center, np.prod(center.shape)) )

        # try this instead:
        absDepthDev = 14
        frame = np.where(abs(frame-medVal) <= absDepthDev, 128, 0).astype(np.uint8)

        # morphological
        kernel = np.ones((3,3), np.uint8)
        frame = cv2.morphologyEx(frame, cv2.MORPH_CLOSE, kernel)

        # connected component
        smallKernel = 3
        frame[self.imgHeight/2-smallKernel:self.imgHeight/2+smallKernel,
            self.imgWidth/2-smallKernel:self.imgWidth/2+smallKernel] = 128

        mask = np.zeros((self.imgHeight+2,self.imgWidth+2), np.uint8)
        flood = frame.copy()
        cv2.floodFill(flood, mask, (self.imgWidth/2,self.imgHeight/2), 255, flags=4|(255<<8))

        ret,flooded = cv2.threshold(flood, 129, 255, cv2.THRESH_BINARY)

        return flooded 
Example 25
Project: VTuber_Unity   Author: kwea123   File: misc.py    License: MIT License 5 votes vote down vote up
def detect_iris(frame, marks, side='left'):
    """
    return:
       x: the x coordinate of the iris.
       y: the y coordinate of the iris.
       x_rate: how much the iris is toward the left. 0 means totally left and 1 is totally right.
       y_rate: how much the iris is toward the top. 0 means totally top and 1 is totally bottom.
    """
    mask = np.full(frame.shape[:2], 255, np.uint8)
    if side == 'left':
        region = marks[36:42].astype(np.int32)
    elif side == 'right':
        region = marks[42:48].astype(np.int32)
    try:
        cv2.fillPoly(mask, [region], (0, 0, 0))
        eye = cv2.bitwise_not(frame, frame.copy(), mask=mask)
        # Cropping on the eye
        margin = 4
        min_x = np.min(region[:, 0]) - margin
        max_x = np.max(region[:, 0]) + margin
        min_y = np.min(region[:, 1]) - margin
        max_y = np.max(region[:, 1]) + margin

        eye = eye[min_y:max_y, min_x:max_x]
        eye = cv2.cvtColor(eye, cv2.COLOR_RGB2GRAY)

        eye_binarized = cv2.threshold(eye, np.quantile(eye, 0.2), 255, cv2.THRESH_BINARY)[1]
        contours, _ = cv2.findContours(eye_binarized, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
        contours = sorted(contours, key=cv2.contourArea)
        moments = cv2.moments(contours[-2])
        x = int(moments['m10'] / moments['m00']) + min_x
        y = int(moments['m01'] / moments['m00']) + min_y
        return x, y, (x-min_x-margin)/(max_x-min_x-2*margin), (y-min_y-margin)/(max_y-min_y-2*margin)
    except:
        return 0, 0, 0.5, 0.5 
Example 26
Project: ssai-cnn   Author: mitmul   File: create_dataset.py    License: MIT License 5 votes vote down vote up
def create_merged_map():
    # copy sat images
    for data_type in ['train', 'test', 'valid']:
        out_dir = 'data/mass_merged/%s/sat' % data_type
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        for fn in glob.glob('data/mass_buildings/%s/sat/*.tiff' % data_type):
            shutil.copy(fn, '%s/%s' % (out_dir, os.path.basename(fn)))

    road_maps = dict([(os.path.basename(fn).split('.')[0], fn)
                      for fn in glob.glob('data/mass_roads/*/map/*.tif')])

    # combine map images
    for data_type in ['train', 'test', 'valid']:
        out_dir = 'data/mass_merged/%s/map' % data_type
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        for fn in glob.glob('data/mass_buildings/%s/map/*.tif' % data_type):
            base = os.path.basename(fn).split('.')[0]
            building_map = cv.imread(fn, cv.IMREAD_GRAYSCALE)
            road_map = cv.imread(road_maps[base], cv.IMREAD_GRAYSCALE)
            _, building_map = cv.threshold(
                building_map, 0, 1, cv.THRESH_BINARY)
            _, road_map = cv.threshold(road_map, 0, 1, cv.THRESH_BINARY)
            h, w = road_map.shape
            merged_map = np.zeros((h, w))
            merged_map += building_map
            merged_map += road_map * 2
            merged_map = np.where(merged_map > 2, 2, merged_map)
            cv.imwrite('data/mass_merged/%s/map/%s.tif' % (data_type, base),
                       merged_map)
            print(merged_map.shape, fn)
            merged_map = np.array([np.where(merged_map == 0, 1, 0),
                                   np.where(merged_map == 1, 1, 0),
                                   np.where(merged_map == 2, 1, 0)])
            merged_map = merged_map.swapaxes(0, 2).swapaxes(0, 1)
            cv.imwrite('data/mass_merged/%s/map/%s.png' % (data_type, base),
                       merged_map * 255) 
Example 27
Project: ssai-cnn   Author: mitmul   File: create_dataset.py    License: MIT License 5 votes vote down vote up
def create_single_maps(map_data_dir):
    for map_fn in glob.glob('%s/*.tif*' % map_data_dir):
        map = cv.imread(map_fn, cv.IMREAD_GRAYSCALE)
        _, map = cv.threshold(map, 0, 1, cv.THRESH_BINARY)
        cv.imwrite(map_fn, map) 
Example 28
Project: airport   Author: cfircohen   File: solver.py    License: Apache License 2.0 5 votes vote down vote up
def PrepareImage(image):
  """Converts color image to black and white"""
  # work on gray scale
  bw = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

  # remove noise, preserve edges
  bw = cv2.bilateralFilter(bw, 9, 75, 75)

  # binary threshold
  bw = cv2.adaptiveThreshold(bw, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                             cv2.THRESH_BINARY, 11, 2)
  return bw 
Example 29
Project: airport   Author: cfircohen   File: solver.py    License: Apache License 2.0 5 votes vote down vote up
def ShowSolution(images, puzzle, solution, frame, box):
  cell_size = np.array([box.w / 4, box.h / 4])
  for piece_type, piece, i, j in solution:
    top_left_loc = np.array([box.x, box.y]) + (np.array([j, i]) -
                                               np.array([1, 1])) * cell_size
    color = pieces.Colors[piece_type]
    piece_img = np.zeros_like(frame)
    for square in itertools.product(range(2), range(2)):
      if piece[square] == board.SquareType.AIR:
        continue

      loc = top_left_loc + np.array(square[::-1]) * cell_size
      piece_img = cv2.rectangle(piece_img, tuple(loc), tuple(loc + cell_size),
                                color, -2)

      if piece[square] in images:
        image = cv2.resize(images[piece[square]], tuple(cell_size))
        blend = np.zeros_like(piece_img)
        blend[loc[1]:loc[1] + cell_size[1], loc[0]:loc[0] + cell_size[
            0]] = image
        piece_img = cv2.addWeighted(piece_img, 1.0, blend, 1.0, 0)

    piece_gray = cv2.cvtColor(piece_img, cv2.COLOR_RGB2GRAY)
    _, piece_gray = cv2.threshold(piece_gray, 10, 255, cv2.THRESH_BINARY)
    _, contours, _ = cv2.findContours(piece_gray, cv2.RETR_EXTERNAL,
                                      cv2.CHAIN_APPROX_SIMPLE)
    piece_img = cv2.drawContours(piece_img, contours, -1, (255, 255, 255), 3)

    frame = cv2.addWeighted(frame, 1.0, piece_img, 0.7, 0)
    cv2.imshow("Planes", frame) 
Example 30
def __init__(self, args, header_dir, ori_img_path):
        """
        :param args: 配置参数
        :param header_dir: 数据文件存放目录
        :param ori_img_path: 原始数据(切割和旋转之后)的路径
        """
        self.header_dir = header_dir
        self.ori_img_path = ori_img_path
        self.args = args
        self.rematch = False
        self.pool_num = int(args.pool_num)
        self.gan_ids = args.gan_ids
        self.pixel_mode = args.gan_chu
        dirs = ["chusai_data_for_watermark_remove/test", "fuusai_data_for_watermark_remove/test", "gan_result_chu_dir",
                "gan_result_fu_dir", "recover_image_chu_dir", "recover_image_fu_dir", "train_data_dir",
                "test_data_preprocessed", "test_data_txts"]
        self.test_data_dst_path = os.path.join(header_dir, "chusai_data_for_watermark_remove")
        self.gan_result_dir = os.path.join(header_dir, "gan_result_chu_dir")
        self.recover_image_dir = os.path.join(header_dir, "recover_image_chu_dir")
        self.train_data_dir = os.path.join(header_dir, "train_data_dir")
        self.fix_bak_data_dir = os.path.join(header_dir, "fix_bak_data")
        self.preprocessed_dir = os.path.join(header_dir, "test_data_preprocessed")
        self.test_data_txts_dir = os.path.join(header_dir, "test_data_txts")
        self.roi_img_path = './watermask_remover_and_split_data/template_imgs/chusai_watermask_template.jpg'
        self.roi_rematch_img_path = "./watermask_remover_and_split_data/template_imgs/fusai_watermask_template.jpg"
        self.base_template = "./watermask_remover_and_split_data/template_imgs/origin_img_location_marker_template.jpg"
        for sub_dir in dirs:
            if not os.path.exists(os.path.join(header_dir, sub_dir)):
                os.makedirs(os.path.join(header_dir, sub_dir))
        ret, roi_img_bin = cv2.threshold(cv2.cvtColor(cv2.imread(self.roi_img_path), cv2.COLOR_RGB2GRAY), 175, 255,
                                         cv2.THRESH_BINARY)
        self.width, self.height = roi_img_bin.shape[::-1]