一. 定义:
4-连接数
4-连接数用于显示像素的状态和附近像素的状态。对于中心像素x_0(x,y),它的邻域定义如下:
S的取值范围为[0,4]:
① S=0:内部点或孤点
② S=1:端点
③ S=2:连接点
④ S=3:分支点
⑤ S=4:交叉点
对4-连接数得到的不同位置的像素点进行着色,能够让我们清晰地观察到像素点所处的不同位置(可参考本文实验结果)。
8-连接数:只需要将二值图像的0和1进行反转,然后进行和4-连接数一样的计算即可。
二. 实验:对图像进行4-连接数着色
源码:
import cv2 import numpy as np import matplotlib.pyplot as plt # Connect 4 def connect_4(img): # get shape H, W, C = img.shape # prepare temporary image tmp = np.zeros((H, W), dtype=np.int) # binarize tmp[img[..., 0] > 0] = 1 # prepare out image out = np.zeros((H, W, 3), dtype=np.uint8) # each pixel for y in range(H): for x in range(W): if tmp[y, x] < 1: continue S = 0 S += (tmp[y,min(x+1,W-1)] - tmp[y,min(x+1,W-1)] * tmp[max(y-1,0),min(x+1,W-1)] * tmp[max(y-1,0),x]) S += (tmp[max(y-1,0),x] - tmp[max(y-1,0),x] * tmp[max(y-1,0),max(x-1,0)] * tmp[y,max(x-1,0)]) S += (tmp[y,max(x-1,0)] - tmp[y,max(x-1,0)] * tmp[min(y+1,H-1),max(x-1,0)] * tmp[min(y+1,H-1),x]) S += (tmp[min(y+1,H-1),x] - tmp[min(y+1,H-1),x] * tmp[min(y+1,H-1),min(x+1,W-1)] * tmp[y,min(x+1,W-1)]) # 孤点 if S == 0: out[y,x] = [0, 0, 255] # 最外端点 elif S == 1: out[y,x] = [0, 255, 0] # 连接点 elif S == 2: out[y,x] = [255, 0, 0] # 分支点 elif S == 3: out[y,x] = [255, 255, 0] # 交叉点 elif S == 4: out[y,x] = [255, 0, 255] out = out.astype(np.uint8) return out # Read image img = cv2.imread("../connect8.png").astype(np.float32) # connect 4 out = connect_4(img) # Save result cv2.imwrite("out.png", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
三. 实验结果:
四. 实验:对图像进行8-连接数着色
源码:
import cv2 import numpy as np import matplotlib.pyplot as plt # connect 8 def connect_8(img): # get shape H, W, C = img.shape # prepare temporary _tmp = np.zeros((H, W), dtype=np.int) # get binarize _tmp[img[..., 0] > 0] = 1 # inverse for connect 8 tmp = 1 - _tmp # prepare image out = np.zeros((H, W, 3), dtype=np.uint8) # each pixel for y in range(H): for x in range(W): if _tmp[y, x] < 1: continue S = 0 S += (tmp[y,min(x+1,W-1)] - tmp[y,min(x+1,W-1)] * tmp[max(y-1,0),min(x+1,W-1)] * tmp[max(y-1,0),x]) S += (tmp[max(y-1,0),x] - tmp[max(y-1,0),x] * tmp[max(y-1,0),max(x-1,0)] * tmp[y,max(x-1,0)]) S += (tmp[y,max(x-1,0)] - tmp[y,max(x-1,0)] * tmp[min(y+1,H-1),max(x-1,0)] * tmp[min(y+1,H-1),x]) S += (tmp[min(y+1,H-1),x] - tmp[min(y+1,H-1),x] * tmp[min(y+1,H-1),min(x+1,W-1)] * tmp[y,min(x+1,W-1)]) if S == 0: out[y,x] = [0, 0, 255] elif S == 1: out[y,x] = [0, 255, 0] elif S == 2: out[y,x] = [255, 0, 0] elif S == 3: out[y,x] = [255, 255, 0] elif S == 4: out[y,x] = [255, 0, 255] out = out.astype(np.uint8) return out # Read image img = cv2.imread("../connect8.png").astype(np.float32) # connect 8 out = connect_8(img) # Save result cv2.imwrite("out.png", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
五. 实验结果:
六. 写在最后的话:
如果您觉得本文对您有所帮助,记得点赞哦!
七. 版权声明:
未经作者允许,请勿随意转载抄袭,抄袭情节严重者,作者将考虑追究其法律责任,创作不易,感谢您的理解和配合!