图像分割(python)

1、图像自动阈值分割(skimage库)

from skimage import data,filters
import matplotlib.pyplot as plt
image=data.camera()
thresh=filters.threshold_otsu(image)
# print(thresh)
dst=(image>=thresh)*1.0
plt.figure("thresh",figsize=(8,8))
plt.subplot(121),plt.title("original image")
plt.imshow(img,plt.cm.gray)
plt.subplot(122),plt.title("binary image")
plt.imshow(dst,"gray")
plt.show()

thresh=filters.threshold_isodata(image)#效果与otsu一样
dst=(image<=thresh)*1.0
plt.figure("thresh",figsize=(8,8))
plt.subplot(121),plt.title("original image")
plt.imshow(img,plt.cm.gray)
plt.subplot(122),plt.title("binary image")
plt.imshow(dst,"gray")
plt.show()

thresh=filters.threshold_li(image)
dst=(image<=thresh)*1.0
plt.figure("thresh",figsize=(8,8))
plt.subplot(121),plt.title("original image")
plt.imshow(img,plt.cm.gray)
plt.subplot(122),plt.title("binary image")
plt.imshow(dst,"gray")
plt.show()

thresh=filters.threshold_yen(image)
dst=(image<=thresh)*1.0
plt.figure("thresh",figsize=(8,8))
plt.subplot(121),plt.title("original image")
plt.imshow(img,plt.cm.gray)
plt.subplot(122),plt.title("binary image")
plt.imshow(dst,"gray")
plt.show()

from skimage import data,filters
import matplotlib.pyplot as plt
image = data.camera()
dst =filters.threshold_adaptive(image, 15) #返回一个阈值图像
# dst1 =filters.threshold_adaptive(image,31,'mean') 
# dst2 =filters.threshold_adaptive(image,5,'median')
# dst2 =filters.threshold_adaptive(image,5,'gussian')
plt.figure('thresh',figsize=(8,8))

plt.subplot(121)
plt.title('original image')
plt.imshow(image,plt.cm.gray)

plt.subplot(122)
plt.title('binary image')
plt.imshow(dst,plt.cm.gray)
plt.show()
#可以修改block_size的大小和method值来查看更多的效果

2、图像全局阈值分割(cv2库)

全局阈值分割设定了一个全局阈值,实现原理为将图像像素值大于或小于该全局阈值的部分作相应处理,将大于阈值的部分设为一个值,小于阈值的部分设为一个值,常用的处理方法由以下5种:

1、cv2.threshold(img_original,thresh,255,cv2.THRESH_BINARY)

原理:二进制阈值化,非黑即白

2、cv2.threshold(img_original,thresh,255,cv2.THRESH_BINARY_INV)

原理:反二进制阈值化,非白即黑

3、cv2.threshold(img_original,thresh,255,cv2.THRESH_TRUNC)

原理:截断阈值化 ,大于阈值设为阈值

4、cv2.threshold(img_original,thresh,255,cv2.THRESH_TOZERO)

原理:阈值化为0 ,小于阈值设为0

5、cv2.threshold(img_original,thresh,255,cv2.THRESH_TOZERO_INV)

原理:反阈值化为0 ,大于阈值设为0

import cv2
import matplotlib.pyplot as plt
#设定阈值
thresh=130
#载入原图,并转化为灰度图像
img_original=cv2.imread('dog.jpg',0)
img_original=cv2.resize(img_original,(0,0),fx=0.3,fy=0.3)
#采用5种阈值类型(thresholding type)分割图像
retval1,img_binary=cv2.threshold(img_original,thresh,255,cv2.THRESH_BINARY)
retval2,img_binary_invertion=cv2.threshold(img_original,thresh,255,cv2.THRESH_BINARY_INV)
retval3,img_trunc=cv2.threshold(img_original,thresh,255,cv2.THRESH_TRUNC)
retval4,img_tozero=cv2.threshold(img_original,thresh,255,cv2.THRESH_TOZERO)
retval5,img_tozero_inversion=cv2.threshold(img_original,thresh,255,cv2.THRESH_TOZERO_INV)
#采用plt.imshow()显示图像
imgs=[img_original,img_binary,img_binary_invertion,img_trunc,img_tozero,img_tozero_inversion]
titles=['original','binary','binary_inv','trunc','tozero','tozero_inv']
plt.figure(figsize=(7,6))
for i in range(6):
    plt.subplot(2,3,i+1)
    plt.imshow(imgs[i],'gray')
    plt.title(titles[i])
    plt.xticks([])
    plt.yticks([])
plt.show()

3、自适应阈值分割(cv2)

由于同一副图像的不同不为光照情况可能不同,因此使用全局阈值可能会导致部分信息丢失,自适应阈值是根据图像的一小块区域计算该区域的阈值,结果更好。dst = cv2.adaptiveThreshold(src, maxval, thresh_type, type, Block Size, C)。其中maxval为填充色,thresh_type为阈值类型,Block Size为分快的大小,C为阈值计算方法中的常数项。

cv2.ADAPTIVE_THRESH_MEAN_C:通过平均的方法取得平均值

cv2.ADAPTIVE_THRESH_GAUSSIAN_C:通过高斯取得高斯值

import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('dog.jpg',0)
# 中值滤波
img = cv2.medianBlur(img,5)
ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
#11 为 Block size, 2 为 C 值
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
cv2.THRESH_BINARY,11,2)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,11,2)
titles = ['Original Image', 'Global Thresholding (v = 127)',
'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in range(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

4、Otsu’s 二值化(大津阈值分割法-cv2库自带)

Otsu’s 二值化是对一副双峰图像自动根据其直方图计算出一个阈值。(对于非双峰图像,这种方法得到的结果可能会不理想)。这里用到到的函数还是 cv2.threshold(),但是需要多传入一个参数
(flag): cv2.THRESH_OTSU。这时要把阈值设为 0。然后算法会找到最优阈值,这个最优阈值就是返回值 retVal。如果不使用 Otsu 二值化,返回的retVal 值与设定的阈值相等。

import cv2
import numpy as np
from matplotlib import pyplot as plt
#cv2自带的otsu
img = cv2.imread('dog.jpg',0)
# global thresholding
ret1,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
# Otsu's thresholding
ret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# Otsu's thresholding after Gaussian filtering
blur = cv2.GaussianBlur(img,(5,5),0)
ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# plot all the images and their histograms
images = [img, 0, th1,
          img, 0, th2,
          blur, 0, th3]
titles = ['Original Noisy Image','Histogram','Global Thresholding (v=127)',
          'Original Noisy Image','Histogram',"Otsu's Thresholding",
          'Gaussian filtered Image','Histogram',"Otsu's Thresholding"]
plt.figure(figsize=(7,6))
for i in range(3):
    plt.subplot(3,3,i*3+1),plt.imshow(images[i*3],'gray')
    plt.title(titles[i*3]), plt.xticks([]), plt.yticks([])
    plt.subplot(3,3,i*3+2),plt.hist(images[i*3].ravel(),256)
    plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([])
    plt.subplot(3,3,i*3+3),plt.imshow(images[i*3+2],'gray')
    plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])
plt.show()

5、otsu阈值分割-最大方差分割(自定义函数)

import matplotlib.pyplot as plt
import numpy as np
import cv2
img=cv2.imread("dog.jpg")
img_gray=cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
img_gray_array=np.array(img_gray)
g_max=0
t_final=0
N=img_gray_array.size#图像总像素点
for t in range(0,255):#历所有从0到255灰度级的阈值分割条件,测试哪一个的类间方差最大
    img_n0=np.where(img_gray_array>t,0,img_gray_array)
    img_n1=np.where(img_gray_array<t,0,img_gray_array)
    n0=np.sum(img_n0!=0)
    n1=np.sum(img_n1!=0)
    w0=n0/N#每个灰度值所占总像素比例
    w1=n1/N
    u0=np.sum(img_n0)/n0
    u1=np.sum(img_n1)/n1
    g=w0*w1*(u0-u1)**2
    if g>g_max:
        g_max=g#如果当前的最大类间方差值最大,则将当前类间方差值作为最大类间方差值
        t_final=t#时的阈值作为最佳阈值
img_gray_array[img_gray_array>t_final]=255
img_gray_array[img_gray_array<=t_final]=0
plt.imshow(img_gray_array,cmap="gray")
plt.title("otsu's Thresholding")

6、最大熵阈值分割

计算所有分割阈值下的图像总熵,找到最大的熵,将最大熵对应的分割阈值作为最终的阈值,图像中灰度大于此阈值的像素作为前景,否则作为背景。$p_{0}(q),p_{1}(q)$分别表示的是q阈值分割的背景和前景像素的累计概率,两者之和为1。背景和前景对应的熵表示如下:

$$H_{0}(q)=-\sum_{i=0}^{q}\frac{p(i)}{p_{0}(q)}log(\frac{p(i)}{p_{0}(q)})$$

$$H_{1}(q)=-\sum_{i=q+1}^{K-1}\frac{p(i)}{p_{1}(q)}log(\frac{p(i)}{p_{1}(q)})$$

在该阈值下,图像总熵为:

$$H(q)=H_{0}(q)+H_{1}(q)$$

 

import numpy as np
import cv2
import matplotlib.pyplot as plt
def segment(img):
    """
    最大熵分割
    :param img:
    :return:
    """
    def calculate_current_entropy(hist, threshold):
        data_hist = hist.copy()
        background_sum = 0.
        target_sum = 0.
        for i in range(256):
            if i < threshold:  # 累积背景
                background_sum += data_hist[i]
            else:  # 累积目标
                target_sum += data_hist[i]
        background_ent = 0.
        target_ent = 0.
        for i in range(256):
            if i < threshold:  # 计算背景熵
                if data_hist[i] == 0:
                    continue
                ratio1 = data_hist[i] / background_sum
                background_ent -= ratio1 * np.log2(ratio1)
            else:
                if data_hist[i] == 0:
                    continue
                ratio2 = data_hist[i] / target_sum
                target_ent -= ratio2 * np.log2(ratio2)
        return target_ent + background_ent

    def max_entropy_segmentation(img):
        channels = [0]
        hist_size = [256]
        prange = [0, 256]
        hist = cv2.calcHist(img, channels, None, hist_size, prange)
        hist = np.reshape(hist, [-1])
        max_ent = 0.
        max_index = 0
        for i in range(256):
            cur_ent = calculate_current_entropy(hist, i)
            if cur_ent > max_ent:
                max_ent = cur_ent
                max_index = i
        ret, th = cv2.threshold(img, max_index, 255, cv2.THRESH_BINARY)
        return th
    img = max_entropy_segmentation(img)
    return img
image=cv2.imread("dog.jpg",0)
image=segment(image)
plt.imshow(image,"gray")

7、迭代阈值分割

根据阈值T将图像分为两组像素度值,新的阈值T0等于两组像素平均值得和除以2,若新阈值减旧阈值差值为零,则为二值图最佳阈值,否则继续迭代,直到满足条件,迭代次数为经验值。

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
# 转灰
def rgb2gray(img):
    h=img.shape[0]
    w=img.shape[1]
    img1=np.zeros((h,w),np.uint8)
    for i in range(h):
        for j in range(w):
            img1[i,j]=0.144*img[i,j,0]+0.587*img[i,j,1]+0.299*img[i,j,2]
    return img1

# 计算新阈值
def threshold(img,T):
    h=img.shape[0]
    w=img.shape[1]
    G1=G2=0
    g1=g2=0
    for i in range (h):
        for j in range (w):
            if img[i,j]>T:
                G1+=img[i,j]
                g1+=1
            else:
                G2+=img[i,j]
                g2+=1
    m1=int(G1/g1)
    m2=int(G2/g2)   # m1,m2计算两组像素均值
    T0=int((m1+m2)/2)   # 据公式计算新的阈值
    return T0

def decide(img,T):
    h=img.shape[0]
    w=img.shape[1]
    img1=np.zeros((h,w),np.uint8)
    T0=T
    T1=threshold(img,T0)
    for k in range (100):   # 迭代次数为经验值,可据实际情况选定
        if abs(T1-T0)==0:   # 若新阈值减旧阈值差值为零,则为二值图最佳阈值
            for i in range (h):
                for j in range (w):
                    if img[i,j]>T1:
                        img1[i,j]=255
                    else:
                        img1[i,j]=0
            break
        else:
            T2=threshold(img,T1)
            T0=T1
            T1=T2   # 变量转换,保证if条件为新阈值减旧阈值
    return img1

image=cv.imread("dog.jpg")
grayimage=rgb2gray(image)
thresholdimage=decide(grayimage,127)
cv.imshow("image",image)
cv.imshow("grayimage",grayimage)
cv.imshow("thresholdimage",thresholdimage)
cv.waitKey(0)
cv.destroyAllWindows()
# plt.subplot(221),plt.imshow(image,plt.cm.gray),plt.title("image"),plt.axis("off")
# plt.subplot(222),plt.imshow(grayimage,plt.cm.gray),plt.title("grayimage")
# plt.subplot(223),plt.imshow(thresholdimage,plt.cm.gray),plt.title("thresholdimage")

 

  • 6
    点赞
  • 86
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值