当前位置: 首页>>代码示例>>Python>>正文


Python cv2.THRESH_BINARY_INV属性代码示例

本文整理汇总了Python中cv2.THRESH_BINARY_INV属性的典型用法代码示例。如果您正苦于以下问题:Python cv2.THRESH_BINARY_INV属性的具体用法?Python cv2.THRESH_BINARY_INV怎么用?Python cv2.THRESH_BINARY_INV使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在cv2的用法示例。


在下文中一共展示了cv2.THRESH_BINARY_INV属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: binary_image

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def binary_image(self,img):
        # 应用5种不同的阈值方法
        # ret, th1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
        # ret, th2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
        # ret, th3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
        # ret, th4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
        # ret, th5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)
        # titles = ['Gray', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
        # images = [img_gray, th1, th2, th3, th4, th5]
        # 使用Matplotlib显示
        # for i in range(6):
        #     plt.subplot(2, 3, i + 1)
        #     plt.imshow(images[i], 'gray')
        #     plt.title(titles[i], fontsize=8)
        #     plt.xticks([]), plt.yticks([])  # 隐藏坐标轴
        # plt.show()

        # Otsu阈值
        _, th = cv2.threshold(img, 0, 255, cv2.THRESH_TOZERO + cv2.THRESH_OTSU)
        cv2.imshow('Binary image', th)
        return th

    # 边缘检测 
开发者ID:CherryXuan,项目名称:Pointer-meter-identification-and-reading,代码行数:25,代码来源:MeterReader.py

示例2: compute_error

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def compute_error(flow, gt_flow, invalid_mask):

    mag_flow = cv2.sqrt(gt_flow[:, :, 0] * gt_flow[:, :, 0] + gt_flow[:, :, 1] * gt_flow[:, :, 1])


    ret, mask_to_large = cv2.threshold(src=mag_flow, thresh=900, maxval=1,                                   type=cv2.THRESH_BINARY_INV)

    total_inp_mask = invalid_mask[:, :, 0] + invalid_mask[:, :, 1] + invalid_mask[:, :, 2]
    ret, fg_mask = cv2.threshold(src=invalid_mask[:, :, 1], thresh=0.5, maxval=1,
                                        type=cv2.THRESH_BINARY)
    ret, total_mask = cv2.threshold(src=total_inp_mask, thresh=0.5, maxval=1,
                                        type=cv2.THRESH_BINARY)
    #mask_to_large = np.ones(fg_mask.shape)
    bg_mask = total_mask - fg_mask
    ee_base = computeEE(flow, gt_flow)
    result = dict()
    result["FG"] = computer_errors(ee_base, fg_mask * mask_to_large)
    result["BG"] = computer_errors(ee_base, bg_mask * mask_to_large)
    result["Total"] = computer_errors(ee_base, total_mask * mask_to_large)
    return result 
开发者ID:tsenst,项目名称:CrowdFlow,代码行数:22,代码来源:util.py

示例3: prepare

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def prepare(input):
    # preprocessing the image input
    clean = cv2.fastNlMeansDenoising(input)
    ret, tresh = cv2.threshold(clean, 127, 1, cv2.THRESH_BINARY_INV)
    img = crop(tresh)

    # 40x10 image as a flatten array
    flatten_img = cv2.resize(img, (40, 10), interpolation=cv2.INTER_AREA).flatten()

    # resize to 400x100
    resized = cv2.resize(img, (400, 100), interpolation=cv2.INTER_AREA)
    columns = np.sum(resized, axis=0)  # sum of all columns
    lines = np.sum(resized, axis=1)  # sum of all lines

    h, w = img.shape
    aspect = w / h

    return [*flatten_img, *columns, *lines, aspect] 
开发者ID:gnbaron,项目名称:signature-recognition,代码行数:20,代码来源:preprocessor.py

示例4: DeleteNotArea

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
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)] 
开发者ID:SunskyF,项目名称:EasyPR-python,代码行数:26,代码来源:plate_locate.py

示例5: compare_ssim_debug

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def compare_ssim_debug(image_a, image_b, color=(255, 0, 0)):
    """
    Args:
        image_a, image_b: opencv image or PIL.Image
        color: (r, g, b) eg: (255, 0, 0) for red

    Refs:
        https://www.pyimagesearch.com/2017/06/19/image-difference-with-opencv-and-python/
    """
    ima, imb = conv2cv(image_a), conv2cv(image_b)
    score, diff = compare_ssim(ima, imb, full=True)
    diff = (diff * 255).astype('uint8')
    _, thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)

    cv2color = tuple(reversed(color))
    im = ima.copy()
    for c in cnts:
        x, y, w, h = cv2.boundingRect(c)
        cv2.rectangle(im, (x, y), (x+w, y+h), cv2color, 2)
    # todo: show image
    cv2pil(im).show()
    return im 
开发者ID:openatx,项目名称:uiautomator2,代码行数:26,代码来源:image.py

示例6: find_marker_ellipses

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def find_marker_ellipses(im):
    im_gray = cvtColor(im, COLOR_BGR2GRAY)
    im_blur = GaussianBlur(im_gray, (3, 3), 0)
    ret, th = threshold(im_blur, 0, 255, THRESH_BINARY_INV + THRESH_OTSU)
    imgEdge, contours, hierarchy = findContours(th, RETR_TREE, CHAIN_APPROX_NONE)
    points = []
    origins = []
    ellipses = []
    id_point_candidates = []
    small_point_candidates = []
    for cnt in contours:
        if contour_sanity_check(cnt, im.shape[0], point_d=0.02):
            id_point_candidates.append(cnt)
        elif contour_sanity_check(cnt, im.shape[0], point_d=0.01):
            small_point_candidates.append(cnt)
    for cnt in id_point_candidates:
        x, y, w, h = boundingRect(cnt)
        ellipse = fitEllipse(cnt)
        points.append(im_gray[y:y + h, x:x + w])
        origins.append((x, y))
        ellipses.append(ellipse)
    return points, origins, ellipses 
开发者ID:pinae,项目名称:Zozo-Measurer,代码行数:24,代码来源:markers.py

示例7: main

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def main():
    threshold = 0
    max_value = 255

    image = cv2.imread("../data/7.1.08.tiff", 0)

    # when applying OTSU threshold, set threshold to 0.

    _, output1 = cv2.threshold(image, threshold, max_value, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    _, output2 = cv2.threshold(image, threshold, max_value, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    _, output3 = cv2.threshold(image, threshold, max_value, cv2.THRESH_TOZERO + cv2.THRESH_OTSU)
    _, output4 = cv2.threshold(image, threshold, max_value, cv2.THRESH_TOZERO_INV + cv2.THRESH_OTSU)
    _, output5 = cv2.threshold(image, threshold, max_value, cv2.THRESH_TRUNC + cv2.THRESH_OTSU)

    images = [image, output1, output2, output3, output4, output5]
    titles = ["Orignals", "Binary", "Binary Inverse", "TOZERO", "TOZERO INV", "TRUNC"]

    for i in range(6):
        plt.subplot(3, 2, i + 1)
        plt.imshow(images[i], cmap='gray')
        plt.title(titles[i])

    plt.show() 
开发者ID:amarlearning,项目名称:Finger-Detection-and-Tracking,代码行数:25,代码来源:OTSUThresholding.py

示例8: clean

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def clean(img):
    """Process an image"""
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    (__, img_bw) = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)

    ctrs, __ = cv2.findContours(img_bw.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # take largest contour
    ctr = sorted(ctrs, key=lambda ctr: (cv2.boundingRect(ctr)[2] * cv2.boundingRect(ctr)[3]),
                 reverse=True)[0]
    # Get bounding box
    x, y, w, h = cv2.boundingRect(ctr)

    # Getting ROI
    roi = img_bw[y:y + h, x:x + w]
    return skeletize(crop(roi, IMAGE_SIZE)) 
开发者ID:hadeeb,项目名称:malayalam-character-recognition,代码行数:18,代码来源:functions.py

示例9: _do_ncs_infer

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def _do_ncs_infer(self, operand, img_label=None):
        """Detect and classify digits. If you provide an img_label the cropped digit image will be written to file."""
        # Get a list of rectangles for objects detected in this operand's box
        op_img = self._canvas[operand.top: operand.bottom, operand.left: operand.right]
        gray_img = cv2.cvtColor(op_img, cv2.COLOR_BGR2GRAY)
        _, binary_img = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY_INV)
        contours, hierarchy = cv2.findContours(binary_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        digits = [cv2.boundingRect(contour) for contour in contours]

        if len(digits) > 0:
            x, y, w, h = digits[0]
            digit_img = self._canvas[operand.top + y: operand.top + y + h,
                                     operand.left + x: operand.left + x + w]

            # Write the cropped image to file if a label was provided
            if img_label:
                cv2.imwrite(img_label + ".png", digit_img)

            # Classify the digit and return the most probable result
            value, probability = self._net_processor.do_async_inference(digit_img)[0]
            print("value: " + str(value) + " probability: " + str(probability))
            return value, probability
        else:
            return None, None 
开发者ID:movidius,项目名称:ncappzoo,代码行数:26,代码来源:mnist_calc.py

示例10: extract_color

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def extract_color( src, h_th_low, h_th_up, s_th, v_th ):
    hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(hsv)
    if h_th_low > h_th_up:
        ret, h_dst_1 = cv2.threshold(h, h_th_low, 255, cv2.THRESH_BINARY) 
        ret, h_dst_2 = cv2.threshold(h, h_th_up,  255, cv2.THRESH_BINARY_INV)

        dst = cv2.bitwise_or(h_dst_1, h_dst_2)
    else:
        ret, dst = cv2.threshold(h,   h_th_low, 255, cv2.THRESH_TOZERO) 
        ret, dst = cv2.threshold(dst, h_th_up,  255, cv2.THRESH_TOZERO_INV)
        ret, dst = cv2.threshold(dst, 0, 255, cv2.THRESH_BINARY)

    ret, s_dst = cv2.threshold(s, s_th, 255, cv2.THRESH_BINARY)
    ret, v_dst = cv2.threshold(v, v_th, 255, cv2.THRESH_BINARY)
    dst = cv2.bitwise_and(dst, s_dst)
    dst = cv2.bitwise_and(dst, v_dst)
    return dst 
开发者ID:karaage0703,项目名称:python-image-processing,代码行数:20,代码来源:extract_color.py

示例11: sketch_image

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def sketch_image(img):
    """Sketches the image applying a laplacian operator to detect the edges"""

    # Convert to gray scale
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply median filter
    img_gray = cv2.medianBlur(img_gray, 5)

    # Detect edges using cv2.Laplacian()
    edges = cv2.Laplacian(img_gray, cv2.CV_8U, ksize=5)

    # Threshold the edges image:
    ret, thresholded = cv2.threshold(edges, 70, 255, cv2.THRESH_BINARY_INV)

    return thresholded 
开发者ID:PacktPublishing,项目名称:Mastering-OpenCV-4-with-Python,代码行数:18,代码来源:cartoonizing.py

示例12: processFile

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def processFile(self, img, debug=False):
        """
        Converts input image to grayscale & applies adaptive thresholding.
        """
        img = cv2.GaussianBlur(img,(5,5),0)
        # Convert to HSV
        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        # Convert to grayscale
        gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        # HSV Thresholding
        res,hsvThresh = cv2.threshold(hsv[:,:,0], 25, 250, cv2.THRESH_BINARY_INV)
        # Show adaptively thresholded image
        adaptiveThresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
        # Show both thresholded images
        # cv2.imshow("HSV Thresholded",hsvThresh)

        if debug:
            cv2.imshow("Adaptive Thresholding", adaptiveThresh)

        return img, adaptiveThresh 
开发者ID:nebbles,项目名称:DE3-ROB1-CHESS,代码行数:22,代码来源:mainDetect.py

示例13: run_vercode_boxdetect

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def run_vercode_boxdetect(ver_img, chineseimg_path):
    ver_img = ver_img.replace('\\', '/')
    image = cv2.imread(ver_img, cv2.IMREAD_GRAYSCALE)
    ret, image1 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY_INV)
    box = FindImageBBox(image1)

    imagename = ver_img.split('/')[-1].split('.')[0]
    box_index = 0
    vercode_box_info = []
    cls_vercode_box_info=[]
    bbox = np.array([0,0,0,0])
    for starx,endx in box:
        box_index = box_index +1
        region = image[0:40,starx:endx]
        out_path = chineseimg_path+ imagename +'_'+str(box_index) + '.jpg'
        cv2.imwrite(out_path, region)
        vercode_box_info.append([out_path,bbox])

    cls_vercode_box_info.append(vercode_box_info)
    return cls_vercode_box_info 
开发者ID:pf67,项目名称:GeetChinese_crack,代码行数:22,代码来源:GeetCodeRun.py

示例14: process_data

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def process_data():
    all_data = []
    img_size = 256
    contour_path= os.path.join(c.data_manual, 'manual_contours_ch4', 'contours')
    image_path = os.path.join(c.data_manual, 'manual_contours_ch4', 'images')
    for fn in [f for f in os.listdir(contour_path) if 'jpg' in f]:
        if not os.path.exists(os.path.join(image_path, fn)):
            continue
        img = cv2.imread(os.path.join(image_path, fn), 0)
        img = cv2.resize(img, (img_size,img_size)).reshape(1,1,img_size,img_size)
        label = cv2.imread(os.path.join(contour_path, fn), 0)
        label = cv2.resize(label, (img_size,img_size))
        _,label = cv2.threshold(label, 127,255,cv2.THRESH_BINARY_INV)
        label = label.reshape(1,1,img_size,img_size)/255
        all_data.append([img,label])
    np.random.shuffle(all_data)
    all_imgs = np.concatenate([a[0] for a in all_data], axis=0)
    all_labels = np.concatenate([a[1] for a in all_data], axis=0)
    n = all_imgs.shape[0]
    destpath = os.path.join(c.data_intermediate, 'ch4_{}.hdf5'.format(img_size))
    if os.path.exists(destpath):
        os.remove(destpath)
    u.save_hd5py({'images': all_imgs, 'labels': all_labels}, destpath, 5) 
开发者ID:woshialex,项目名称:diagnose-heart,代码行数:25,代码来源:ch4.py

示例15: hasTable

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import THRESH_BINARY_INV [as 别名]
def hasTable(filename, min_fract_area=.2, min_cells=150):
    img = cv2.imread(filename, flags=cv2.IMREAD_COLOR)
    if img is None:
        raise ValueError("File {0} does not exist".format(filename))
    imgGrey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    imgThresh = cv2.threshold(imgGrey, 150, 255, cv2.THRESH_BINARY_INV)[1]
    imgThreshInv = cv2.threshold(imgGrey, 150, 255, cv2.THRESH_BINARY)[1]

    imgDil = cv2.dilate(imgThresh, np.ones((5, 5), np.uint8))
    imgEro = cv2.erode(imgDil, np.ones((4, 4), np.uint8))

    contour_analyzer = TableRecognition.ContourAnalyzer(imgDil)
    # 1st pass (black in algorithm diagram)
    contour_analyzer.filter_contours(min_area=400)
    contour_analyzer.build_graph()
    contour_analyzer.remove_non_table_nodes()
    contour_analyzer.compute_contour_bounding_boxes()
    contour_analyzer.separate_supernode()

    return contour_analyzer.does_page_have_valid_table(min_fract_area, min_cells) 
开发者ID:ulikoehler,项目名称:OTR,代码行数:22,代码来源:filter-table-pages.py


注:本文中的cv2.THRESH_BINARY_INV属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。