python圖像處理opencv包大型指導

二值化 cv2.threshold

import cv2
import numpy as np
img = cv2.imread('Hydrogen_Density_Plots.png',0)
threshold = 10
maxvalue = 157
print(np.amax(img))
ret_otsu,thresh1 = cv2.threshold(img,threshold,maxvalue,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
ret1,thresh2 = cv2.threshold(img,threshold,maxvalue,cv2.THRESH_BINARY)
cv2.imshow('1',img)
cv2.imshow('otsu',thresh1)
cv2.imshow('binary',thresh2)

threshold參數:大於它全部賦值爲min(maxvalue, 255)

maxvalue參數:一般設爲255,即白色。

ret參數返回爲實際使用的閾值,如otsu方法是自動計算出的閾值。

 

邊界探測Canny, Laplacian, sobel

原理,首先都是二值圖,邊界255,非邊界0。其中Canny是專用的針對邊界探測設計的方法,參數爲threshold1,threshold2。梯度大於閾值2的位置判斷爲邊界,小於閾值1的位置判斷爲非邊界,介於之間的逐個判斷時候互相相連。

 

import cv2

img = cv2.imread('Hydrogen_Density_Plots.png',0)

edges = cv2.Canny(img,threshold1=100,threshold2=200)
laplacian = cv2.Laplacian(img,cv2.CV_64F)
sobely = cv2.Sobel(img,cv2.CV_64F,dx=1,dy=1,ksize=3) 

cv2.imshow('canny',edges)
cv2.imshow('laplacian',laplacian)
cv2.imshow('sobel',sobely)

 

輪廓drawContour

import cv2
import numpy as np

img = cv2.imread('Hydrogen_Density_Plots.png',0)
edges = cv2.Canny(img,threshold1=100,threshold2=200)
binary,contours, hierarchy = cv2.findContours(edges,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) 
a,b=binary.shape
canvas = np.ones((a,b,3),np.uint8)*255
cv2.drawContours(canvas,contours,-1,color=(0,255,0),thickness=3)

cv2.imshow("contours",canvas)

-1表示輪廓全畫,np.ones()生成全白畫布。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章