import numpy as np
import cv2
img=cv2.imread("9.png",0)
cv2.imshow("ori",img)
x=img.shape[0]
y=img.shape[1]
b=np.uint8(np.zeros((x,y)))
for i in range(1,x-1):
for j in range(1,y-1):
if (img[i-1][j-1]==255 and img[i-1][j+1]==255 and img[i+1][j-1]==255 and img[i+1][j+1]==255):
b[i][j]=255
cv2.imshow("Eroded",b) #侵蝕
img=cv2.imread("9.png",0)
c=np.uint8(np.zeros((x,y)))
for i in range(1,x-1):
for j in range(1,y-1):
if (img[i][j]==255):
c[i][j]=255
c[i-1][j-1]=255
c[i+1][j-1]=255
c[i-1][j+1]=255
c[i+1][j+1]=255
cv2.imshow("Dilated",c)#膨脹
d=np.uint8(np.zeros((x,y)))
for i in range(1,x-1):
for j in range(1,y-1):
if (b[i][j]==255):
d[i][j]=255
d[i-1][j-1]=255
d[i+1][j-1]=255
d[i-1][j+1]=255
d[i+1][j+1]=255
cv2.imshow("open",d) #先侵蝕再膨脹-斷開
f=np.uint8(np.zeros((x,y)))
g=np.uint8(np.zeros((x,y)))
for i in range(1,x-1):
for j in range(1,y-1):
if (c[i-1][j-1]==255 and c[i-1][j+1]==255 and c[i+1][j-1]==255 and c[i+1][j+1]==255):
f[i][j]=255
cv2.imshow("close",f) #先膨脹再侵蝕-閉合
img1=cv2.imread("9.png",0)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3, 3))
eroded = cv2.erode(img1,kernel)
dilated = cv2.dilate(img1,kernel)
ret1 = cv2.morphologyEx(img1, cv2.MORPH_OPEN, kernel)
ret2 = cv2.morphologyEx(img1, cv2.MORPH_CLOSE, kernel)
cv2.imshow('opencv-Open Image', ret1)
cv2.imshow('opencv-Close Image', ret2)
cv2.imshow("opencv-Dilated Image",dilated)
cv2.imshow("opencv-Eroded Image",eroded)
cv2.waitKey(0)
cv2.destroyAllWindows()
留言
張貼留言