开运算过程: 1、将图像转化为灰度图。 2、进行大津二值化,利用阈值将原图像分成前景,背景两个图象。 3、开运算则是首先进行N次腐蚀,再进行N次膨胀。开运算可以用来去除仅存的小块像素。 闭运算过程: 1、将图像转化为灰度图。 2、进行大津二值化,利用阈值将原图像分成前景,背景两个图象。 3、闭运算则是先进行N次膨胀,再进行N次腐蚀, 闭运算能够将中断的像素连接起来。
(1)膨胀:如果结果大于255的话,将中心像素设为255 (2)腐蚀:结果小于255×4的话,将中心像素设为0。
实现代码:
import cv2
import numpy as np
class Open_Close:
def __init__(self, img, Dila_times=1, th=128):
self.image = img
self.Dila_time = Dila_times
self.th = th
def BGR2GRAY(self, img):
b = img[:, :, 0].copy()
g = img[:, :, 1].copy()
r = img[:, :, 2].copy()
out = r * 0.2126 + g * 0.7152 + b * 0.0722
out = out.astype(np.uint8)
return out
def otsu_binarization(self, img, th=128):
H, W = img.shape
out = img.copy()
max_sigma = 0
max_t = 0
for _t in range(1, 255):
v0 = out[out < _t]
m0 = np.mean(v0) if len(v0) > 0 else 0
w0 = len(v0) / (H * W)
v1 = out[out >= _t]
m1 = np.mean(v1) if len(v1) > 0 else 0
w1 = len(v1) / (H * W)
sigma = w0 * w1 * ((m0 - m1) ** 2)
if sigma > max_sigma:
max_sigma = sigma
max_t = _t
print(f'Threshold:{max_t}')
th = max_t
out[out < th] = 0
out[out >= th] = 255
return out
#膨胀具体操作
def Morphology_Erode(self, img, Dil_times):
H, W = img.shape
out = img.copy()
MF = np.array(((0, 1, 0),
(1, 0, 1),
(0, 1, 0)), dtype=np.int32)
for i in range(Dil_times):
tmp = np.pad(out, (1, 1), 'edge')
for y in range(1, H+1):
for x in range(1, W+1):
if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) > 255:
out[y-1, x-1] = 255
return out
#腐蚀具体操作
def Morphology_Dilate(self, img, Dil_times):
H, W = img.shape
out = img.copy()
MF = np.array(((0, 1, 0),
(1, 0, 1),
(0, 1, 0)), dtype=np.int32)
for i in range(Dil_times):
tmp = np.pad(out, (1, 1), 'edge')
for y in range(1, H+1):
for x in range(1, W+1):
if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) < 255*4:
out[y-1, x-1] = 0
return out
def open_c(img, s_times):
open_r = Open_Close(img, s_times)
img_gray = open_r.BGR2GRAY(image)
out = open_r.otsu_binarization(img_gray)
dilate_im = open_r.Morphology_Dilate(out, s_times)
result_im = open_r.Morphology_Erode(dilate_im, s_times)
cv2.imshow('Result_img', result_im)
cv2.waitKey(0)
cv2.destroyWindow()
def close_c(img, t_times):
close_r = Open_Close(img, Dila_times=t_times)
img_gray = close_r.BGR2GRAY(img)
out = close_r.otsu_binarization(img_gray)
erod = close_r.Morphology_Erode(out, t_times)
result = close_r.Morphology_Dilate(erod, t_times)
cv2.imshow('result_img', result)
cv2.waitKey(0)
cv2.destroyWindow()
if __name__ == "__main__":
image = cv2.imread('img.png').astype(np.float32)
times = 2
#开运算
open_c(image, times)
#闭运算
#close_c(image, times)