This Chapter is all about image segmentation.
I still not finished whole chapter, but here try to publish some for reference.
这里写目录标题
import sys
import numpy as np
import cv2
import matplotlib
import matplotlib.pyplot as plt
import PIL
from PIL import Image
print(f"Python version: {sys.version}")
print(f"Numpy version: {np.__version__}")
print(f"Opencv version: {cv2.__version__}")
print(f"Matplotlib version: {matplotlib.__version__}")
print(f"Pillow version: {PIL.__version__}")
def normalize(x, ymin=0, ymax=1):
"""
Description:
- Map x into desired range[ymin, ymax], according to the math function
$$y = \frac{(y_{\text{max}} - y_{\text{min}}) (x - x_{\text{min}})}{(x_{\text{max}} - x_{\text{min}})} + y_{\text{min}}$$
Parameters:
- x: input array
- ymin: desired min value, such as -1, or whatever you want
- ymax: desired max value, such as 1, or other you need
"""
result = (ymax - ymin) * (x - x.min()) / (x.max()-x.min()) + ymin
#################### old one ######################
# result = (x - x.min()) / (x.max() - x.min())
return result
基础知识
令 R R R表示一幅图像占据的整个空间区域。我们可以将图像分割视为把 R R R分为 n n n个子区域 R 1 , R 2 , ⋯ , R n R_1,R_2,\cdots,R_n R1,R2,⋯,Rn的过程,满足:
- (a) ⋃ i = 1 n R i = R \bigcup_{i=1}^{n} R_{i} = R ⋃i=1nRi=R。
- (b) R i , i = 0 , 1 , 2 , ⋯ , n R_{i}, i=0, 1, 2, \cdots, n Ri,i=0,1,2,⋯,n 是一个连通集。
- (c) 对所有 i i i和 j j j, i ≠ j , R i ⋂ R j = ∅ i\neq j, R_{i}\bigcap R_{j} = \emptyset i=j,Ri⋂Rj=∅。
- (d) Q ( R i ) = T R U E , i = 0 , 1 , 2 , ⋯ , n Q(R_{i})=TRUE, i=0, 1, 2, \cdots, n Q(Ri)=TRUE,i=0,1,2,⋯,n。
- (e) 对于任何邻接区域 R i R_{i} Ri和 R j R_{j} Rj, Q ( R i ⋃ R j ) = F A L S E Q(R_{i} \bigcup R_{j}) = FALSE Q(Ri⋃Rj)=FALSE。
其中 Q ( R i ) Q(R_{i}) Q(Ri)是定义在集合 R k R_{k} Rk中的点上的一个谓词逻辑。
def std_seg(image, thred=0, stride=4):
"""
Description:
Segment image caculating standard deviation
Paremeters:
image: input grayscale image
thred: thredshold of the standard diviation
stride: control the neighborhood
Return:
Binary segment image
"""
h, w = image.shape[:2]
result = image.copy()
# here we use stride the create non-overlap region, if we not need stride here, we still can get very good result
# or we set stride smaller than 8, then we can get better result
for i in range(0, h, stride):
for j in range(0, w, stride):
temp = image[i:i+stride, j:j+stride]
if np.std(temp) <= thred:
result[i:i+stride, j:j+stride] = 0
else:
result[i:i+stride, j:j+stride] = 255
return result
# standard deviation segment, according the result below, it seems the img_f is not 8x8 region, is about 4-5
img_d = cv2.imread("DIP_Figures/DIP3E_Original_Images_CH10/Fig1001(d)(noisy_region).tif", -1)
img_seg = std_seg(img_d, thred=0, stride=5)
fig = plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1), plt.imshow(img_d, 'gray'), plt.xticks([]), plt.yticks([])
plt.subplot(1, 2, 2), plt.imshow(img_seg, 'gray'), plt.xticks([]), plt.yticks([])
plt.tight_layout()
plt.show()