cv2.threshold() 阈值:使用Python,OpenCV进行简单的图像分割
生活随笔
收集整理的這篇文章主要介紹了
cv2.threshold() 阈值:使用Python,OpenCV进行简单的图像分割
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
圖像分割有多種形式。 聚類、壓縮、邊緣檢測、區域增長、圖分區、分水嶺等等;(Clustering. Compression. Edge detection. Region-growing.
Graph partitioning. Watershed. The list goes on.)
但是最開始只有最基本的一種:就是本文中介紹的 threholding 閾值化
一定要嘗試設置thresh,因為它會根據您提供的thresh值給出不同的結果。
參考:Thresholding: Simple Image Segmentation using OpenCV
cv2.threhold 函數簽名: (T,threshImage)= cv2.threshold(src,thresh,maxval,type)參數:- src:源圖像,或我們要對其執行閾值處理的圖像。此圖像應為灰度。 - thresh:閾值,用于對灰度圖像中的像素強度進行分類。 - maxval:方法種用到的閾值; - type: 要使用的閾值方法。可以為:cv2.THRESH_BINARY cv2.THRESH_BINARY_INV cv2.THRESH_TRUNC cv2.THRESH_TOZERO cv2.THRESH_TOZERO_INV1. cv2.THRESH_BINARY 超過閾值的像素設置為maxVal,不超過的設置為02. cv2.THRESH_BINARY_INV 1的反轉(不超過閾值的像素設置為maxVal,超過的設置為0)3. cv2.THRESH_TRUNC 超過閾值的設為thresh4. cv2.THRESH_TOZERO 低于閥值的設為05. cv2.THRESH_TOZERO_INV (低于閥值的設為maxVal)返回值:- T: 用于閾值化的值,同thresh- threshImage: 閾值化后生成的圖像
原圖:
# python threshold.py --image images/skateboard_decks.png --threshold 245
import argparse
import cv2# --image 是我們要閾值的圖像的路徑。
# --threhold 是將要傳遞到cv2.threshold的閾值
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,help="Path to the image to be thresholded")
ap.add_argument("-t", "--threshold", type=int, default=128,help="Threshold value")
args = vars(ap.parse_args())
# 加載圖片并灰度化【 轉換為灰度,期望一個單通道圖像。】
image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 定義我們的閾值方法列表
methods = [("THRESH_BINARY", cv2.THRESH_BINARY),("THRESH_BINARY_INV", cv2.THRESH_BINARY_INV),("THRESH_TRUNC", cv2.THRESH_TRUNC),("THRESH_TOZERO", cv2.THRESH_TOZERO),("THRESH_TOZERO_INV", cv2.THRESH_TOZERO_INV)]
# 遍歷閾值方法
for (threshName, threshMethod) in methods:# 將255(白色)作為閾值測試時的值作為第三個參數(T, thresh) = cv2.threshold(gray, args["threshold"], 255, threshMethod)cv2.imshow(threshName, thresh)cv2.waitKey(0)
總結
以上是生活随笔為你收集整理的cv2.threshold() 阈值:使用Python,OpenCV进行简单的图像分割的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Python,OpenCV生成Aru
- 下一篇: Python 比较俩张图片差异