python实现阈值化分割,成二值图像【实测成功】

仅作为记录,大佬请跳过。

黑白图像的阈值分割,代码可直接运行

原图像:博主命名为了a3fingerprint.jpg

在这里插入图片描述

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

# 读取图片,转成矩阵
img=plt.imread('a3fingerprint.jpg')
im=np.array(img)

# 矩阵大小
l=len(im)
w=len(im[0])

# 初始阈值
zmin=np.min(im)
zmax=np.max(im)
t0=int((zmin+zmax)/2)

t1=0
res1=0
res2=0
s1=0
s2=0

while abs(t0-t1)>0:
    for i in range(0,l-1):
        for j in range(0,w-1):
            if im[i,j]<t0:
                res1=res1+im[i,j]
                s1=s1+1
            elif im[i,j]>t0:
                res2=res2+im[i,j]
                s2=s2+2
    avg1=res1/s1
    avg2=res2/s2
    res1=0
    res2=0
    s1=0
    s2=0
    t1=t0
    t0=int((avg1+avg2)/2)

# 阈值化
# # 小于阈值t0的像素置0,大于阈值的像素置255
im=np.where(im[...,:]<t0,0,255)

# 显示
# # 原图
plt.figure()
plt.subplot(2,2,1)
plt.imshow(img,cmap='gray')
plt.title('original')

# # #原图直方图
# plt.figure()
plt.subplot(2,2,2)
plt.hist(img.ravel(),256)
plt.title('hist')
plt.axvline(t0)
plt.text(25,6100,'best threshold:{}'.format(t0),size=15,alpha=0.8)

# # # 阈值分割后的图
# plt.figure()
plt.subplot(2,2,3)
plt.imshow(Image.fromarray(im),cmap='gray')
plt.title('new')

# # 阈值分割后的图的直方图
# plt.figure()
plt.subplot(2,2,4)
plt.hist(im.ravel(),256)
plt.title('hist')

plt.show()

展示:

在这里插入图片描述

彩色——代码可直接运行

原图像:博主命名为了a3color.jpg

在这里插入图片描述

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

# 读取图片,转成矩阵
img=plt.imread('a3color.jpg')
im=np.array(img[:,:,2])

# 矩阵大小
l=len(im)
w=len(im[0])

# 初始阈值
zmin=np.min(im)
zmax=np.max(im)
t0=int((zmin+zmax)/2)

t1=0
res1=0
res2=0
s1=0
s2=0

while abs(t0-t1)>0:
    for i in range(0,l-1):
        for j in range(0,w-1):
            if im[i,j]<t0:
                res1=res1+im[i,j]
                s1=s1+1
            elif im[i,j]>t0:
                res2=res2+im[i,j]
                s2=s2+2
    avg1=res1/s1
    avg2=res2/s2
    res1=0
    res2=0
    s1=0
    s2=0
    t1=t0
    t0=int((avg1+avg2)/2)

# 阈值化
# # 小于阈值t0的像素置0,大于阈值的像素置255
im=np.where(im[...,:]<t0,0,255)

# 显示
# # 原图
plt.figure()
plt.subplot(2,2,1)
plt.imshow(img,cmap='gray')
plt.title('original')

# # #原图直方图
# plt.figure()
plt.subplot(2,2,2)
plt.hist(img.ravel(),256)
plt.title('hist')
plt.axvline(t0)
plt.text(25,6100,'best threshold:{}'.format(t0),size=15,alpha=0.8)

# # # 阈值分割后的图
# plt.figure()
plt.subplot(2,2,3)
plt.imshow(Image.fromarray(im),cmap='gray')
plt.title('new')

# # 阈值分割后的图的直方图
# plt.figure()
plt.subplot(2,2,4)
plt.hist(im.ravel(),256)
plt.title('hist')

plt.show()

展示:
在这里插入图片描述

注:

将其用imread加载后,因为是彩色,得到数组是(375,499,3)(3指有三个通道(彩色RGB));只选取其一个通道,博主取的是第三通道。

(另,博主发现取第一通道时,阈值左边的个数迭代后是0,0作为除数导致程序错误,所以博主选取彩色第三通道(彩色第二通道也可以))

在这里插入图片描述

在这里插入图片描述

参考

传送门

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值