图像的二值化,就是将图像上的像素点的灰度值设置为0或255,也就是将整个图像呈现出明显的只有黑和白的视觉效果。
import matplotlib.pyplot as plt
import cv2
import numpy as np
from scipy import ndimage as ndi
from skimage.filters import roberts
#mport cv2.cv as cv
img=cv2.imread('H:\\dicomdata\\cropdata\\1.jpg')
GrayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh1=cv2.threshold(GrayImage,153,255,cv2.THRESH_BINARY)
#ret,thresh2=cv2.threshold(GrayImage,130,255,cv2.THRESH_BINARY_INV)
kernel=np.uint8(np.zeros((5,5)))
for x in range(5):
kernel[x,2]=1;
kernel[2,x]=1;
#腐蚀图像
eroded=cv2.erode(thresh1,kernel);
#膨胀图像
dilated = cv2.dilate(thresh1,kernel)
result = cv2.absdiff(dilated,eroded)
edges = roberts(result)
binary = ndi.binary_fill_holes(edges)
#plt.subplot(2,2,1)
#plt.imshow(thresh1)
#plt.subplot(2,2,2)
#plt.imshow(result)
#opening = cv2.morphologyEx(result, cv2.MORPH_OPEN, kernel)
#closing = cv2.morphologyEx(result, cv2.MORPH_CLOSE, kernel)
plt.imshow(dilated)
#GrayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#ret,thresh1=cv2.threshold(GrayImage,127,255,cv2.THRESH_BINARY)
#ret,thresh2=cv2.threshold(GrayImage,127,255,cv2.THRESH_BINARY_INV)
其他opencv 进行二值化的相关操作
#二值化处理,低于阈值的像素点灰度值置为0;高于阈值的值置为参数3
ret,thresh1 = cv2.threshold(grayImage,127,255,cv2.THRESH_BINARY)
cv2.imshow('BINARY',thresh1)
#大于阈值的像素点灰度值置为0;小于阈值置为参数3
ret,thresh2 = cv2.threshold(grayImage,127,200,cv2.THRESH_BINARY_INV)
cv2.imshow('BINARY_INV',thresh2)
#小于阈值的像素点灰度值不变,大于阈值的像素点置为该阈值
ret,thresh3 = cv2.threshold(grayImage,127,255,cv2.THRESH_TRUNC)
cv2.imshow('TRUNC',thresh3)
#小于阈值的像素点灰度值不变,大于阈值的像素点置为0,其中参数3任取
ret,thresh4 = cv2.threshold(grayImage,127,255,cv2.THRESH_TOZERO)
cv2.imshow('BINARY_TOZERO',thresh4)
#大于阈值的像素点灰度值不变,小于阈值的像素点置为0,其中参数3任取
ret,thresh5 = cv2.threshold(grayImage,127,255,cv2.THRESH_TOZERO_INV)
cv2.imshow('BINARY_TOZERO_INV',thresh5)
参考 python数字图像处理(18):高级形态学处理