天天看點

11、OpenCV圖像二值化處理

Python:​

​cv.​

​​

​Threshold​

​(src, dst, threshold, maxValue, thresholdType) → None

Parameters:
  • src– input array (single-channel, 8-bit or 32-bit floating point).
  • dst– output array of the same size and type as​

    ​src​

    ​.
  • thresh– threshold value.
  • maxval– maximum value to use with the​

    ​THRESH_BINARY​

    ​​ and​

    ​THRESH_BINARY_INV​

    ​ thresholding types.
  • type– thresholding type (see the details below).
  • 11、OpenCV圖像二值化處理
#!/usr/bin/python
#-*- coding:utf-8 -*-

import numpy as np
import cv2

# original image (gray scale image)
org_img = cv2.imread('1.jpg', 0)

# preference
THRESHOLD = 127
MAXVALUE  = 255

# binarization using opencv
_, bin_cv2 = cv2.threshold(org_img, THRESHOLD, MAXVALUE, cv2.THRESH_BINARY)
'''Parameters:  
src – input array (single-channel, 8-bit or 32-bit floating point).
dst – output array of the same size and type as src.
thresh – threshold value.
maxval – maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types.
type – thresholding type (see the details below).
'''
# binarization not using opencv
bin_npy = np.zeros(org_img.shape, org_img.dtype)
bin_npy[np.where(org_img > THRESHOLD)] = MAXVALUE

# check
cv2.imshow('original.png',   org_img)
cv2.imshow('binary_cv2.png', bin_cv2)
cv2.imshow('binary_npy.png', bin_npy)
cv2.waitKey(0)      
11、OpenCV圖像二值化處理