Python-OpenCV 7. 圖像二值化

一、介紹

圖像二值化( Image Binarization)就是將圖像上的像素點的灰度值設置為0或255,也就是將整個圖像呈現出明顯的黑白效果的過程。 

在數字圖像處理中,二值圖像佔有非常重要的地位,圖像的二值化使圖像中數據量大為減少,從而能凸顯出目標的輪廓。
圖像的二值化處理就是將圖像上的點的灰度值為0或255,也就是將整個圖像呈現出明顯的黑白效果。即將256個亮度等級的灰度圖像通過適當的閾值選取而獲得仍然可以反映圖像整體和局部特徵的二值化圖像。

二、實現原理

一幅圖像包括目標物體、背景還有噪聲,要想從多值的數字圖像中直接提取出目標物體,常用的方法就是設定一個閾值T,用T將圖像的數據分成兩部分:大於T的像素群和小於T的像素群。這是研究灰度變換的最特殊的方法,稱為圖像的二值化(Binarization)。

Python-OpenCV中提供了閾值(threshold)函數:

threshold(src, thresh, maxval, type[, dst]) -> retval, dst

函數:

  • src 指原圖像,原圖像應該是灰度圖。
  • thresh 閾值
  • maxval 表示與THRESH_BINARY和THRESH_BINARY_INV閾值類型一起使用設置的最大值
  • type 表示閾值類型
  • retval參數表示返回的閾值。若是全局固定閾值算法,則返回thresh參數值。若是全局自適應閾值算法,則返回自適應計算得出的合適閾值。
  • dst參數表示輸出與src相同大小和類型以及相同通道數的圖像。

cv2.thresh_otsu類型

  • 第一返回值,得到圖像的閾值,
  • 第二個返回值,也就是閾值處理後的圖像,

adaptiveThreshold方法

def adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C, dst=None): # real signature unknown; restored from __doc__

OpenCV的adaptiveThreshold函數進行局部閾值。函數原型為:adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst]) -> dst

  • src參數表示輸入圖像(8位單通道圖像)。
  • maxValue參數表示使用 THRESH_BINARY 和 THRESH_BINARY_INV 的最大值.
  • adaptiveMethod參數表示自適應閾值算法,平均 (ADAPTIVE_THRESH_MEAN_C)或高斯(ADAPTIVE_THRESH_GAUSSIAN_C)。
  • thresholdType參數表示閾值類型,必須為THRESH_BINARY或THRESH_BINARY_INV的閾值類型。
  • blockSize參數表示塊大小(奇數且大於1,比如3,5,7........ )。

C參數是常數,表示從平均值或加權平均值中減去的數。 通常情況下,這是正值,但也可能為零或負值。

三、OpenCV代碼實現

1. OpenCV 閾值函數DEMO

# -*- coding: utf-8 -*-
import cv2
image = cv2.imread('test.jpg')
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
cv2.threshold(image, 140, 255, 0, image)
cv2.imshow("Image", image)
cv2.waitKey(0)

2. 全局閾值使用THRESH_OTSU

# -*- coding: utf-8 -*-
import cv2
image = cv2.imread('test.jpg')
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
ret, binary = cv2.threshold(image, 140, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU, image)
print("threshold value: %s" % ret) # 打印閾值,前面先進行了灰度處理0-255,我們使用該閾值進行處理,低於該閾值的圖像部分全為黑,高於該閾值則為白色
cv2.imshow("Image", binary)
cv2.waitKey(0)
Python-OpenCV 7. 圖像二值化

3. 全局閾值使用THRESH_TRIANGLE 三角形算法

ret, binary = cv.threshold(gray,0,255,cv.THRESH_BINARY | cv.THRESH_TRIANGLE)
Python-OpenCV 7. 圖像二值化

4. 全局閾值,指定閾值,大於指定閾值都為0

ret, binary = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY_INV)
Python-OpenCV 7. 圖像二值化

5. 全局閾值,指定閾值,大於127都為127

ret, binary = cv2.threshold(image, 127, 255, cv2.THRESH_TRUNC)
Python-OpenCV 7. 圖像二值化

6. 全局閾值,小於閾值的都為0

ret, binary = cv2.threshold(image, 127, 255, cv2.THRESH_TOZERO)
Python-OpenCV 7. 圖像二值化

7. 局部閾值 ADAPTIVE_THRESH_MEAN_C

# -*- coding: utf-8 -*-
import cv2
image = cv2.imread('test.jpg')
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
dst = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 25, 10)
cv2.imshow("Image", dst)
cv2.waitKey(0)
Python-OpenCV 7. 圖像二值化

8. 局部閾值ADAPTIVE_THRESH_GAUSSIAN_C

# -*- coding: utf-8 -*-
import cv2
image = cv2.imread('test.jpg')
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
dst = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 25, 10)
cv2.imshow("Image", dst)
cv2.waitKey(0)
Python-OpenCV 7. 圖像二值化

四、numpy運算

1. 使用中間閾值127

# -*- coding: utf-8 -*-
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
# 顯示圖片
def showimg(img, isgray=False):
plt.axis("off")
if isgray == True:
plt.imshow(img, cmap='gray')
else:
plt.imshow(img)
plt.show()
im = Image.open("test.jpg")
im = np.array(im.convert('L'))
im = np.where(im[..., :] < 127, 0, 255)
showimg(Image.fromarray(im), True)
Python-OpenCV 7. 圖像二值化

2. 取所有像素點灰度的平均值

# -*- coding: utf-8 -*-
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
# 顯示圖片
def showimg(img, isgray=False):
plt.axis("off")
if isgray:
plt.imshow(img, cmap='gray')
else:
plt.imshow(img)
plt.show()
im = Image.open("test.jpg")
im = np.array(im.convert('L'))
im = np.array(im)
avg_gray = np.average(im)
im = np.where(im[..., :] < avg_gray, 0, 255)
showimg(Image.fromarray(im), True)
Python-OpenCV 7. 圖像二值化


分享到:


相關文章: