图像阈值分割代码模板

一、手工阈值分割

代码部分:

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

# 图片二值化
img = Image.open('E:/shale10053.bmp')

threshold = 66 #手工设置阈值
table = []
for i in range(256):
    if i < threshold:
        table.append(0)
    else:
        table.append(1)      
       
# 图片二值化
photo = img.point(table, '1')
# photo.save("test2.jpg")
plt.figure(figsize=(5,5))
plt.subplot(), plt.imshow(photo)

运行结果:

  

 二、Otsu法阈值分割

代码部分:

#coding:utf-8
import cv2
import numpy as np
from matplotlib import pyplot as plt

image = cv2.imread('E:/shale10053.bmp')#导入图像
grayimage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)#彩色转灰度
gray = cv2.GaussianBlur(grayimage, (3,3), 0)#进行高斯滤波

ret1, th1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)  #方法选择为THRESH_OTSU

plt.figure(figsize=(5,5))
plt.subplot(), plt.imshow(th1, "gray")
plt.title("Otsu,threshold is " + str(ret1)), plt.xticks([]), plt.yticks([])

 运行结果:

 三、手工双阈值分割

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

#图片三相分割
img_gray = cv2.imread('E:/circular2.bmp',cv2.IMREAD_GRAYSCALE)
cv2.imshow("img_gray", img_gray)
#对比度增强(线性变换)
a = 1.5
img_gray = img_gray * float(a)
img_gray[img_gray > 255] = 255
img_gray = np.round(img_gray)
img_gray =img_gray.astype(np.uint8)

# 绘制直方图
n, bins, patches = plt.hist(img_gray.flatten(), bins=256)
plt.show()

img = img_gray
Threshold1 = 99
Threshold2 = 155
row,col = np.shape(img)        
for i in range(row):
    for j in range(row):
        if img[i, j] > Threshold2:
            img[i, j] = 255
        elif img[i, j] <= Threshold1:
            img[i, j] = 0
        else:
            img[i, j] = 128

cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()

运行结果:

因为手工设置的阈值也没有参考范围,所以这两个阈值是手动调试出来的。为了减少噪声的影响,在图像分割前先对图像做了对比度增强处理,线性变换的值取1.5,对应的两个阈值是<99><72>,如果没有对比度增强这一步的话,原本的两个阈值是<72><99>

四、批量Otsu分割

import os#导入批量处理模块
from PIL import Image#导入图像处理模块
import cv2
import numpy as np
from matplotlib import pyplot as plt

path = r"I:/sandstone2 19.9"#导入图像的路径
filelist =os.listdir (path)#列出路径下所有的文件,并存储在filelist的列表里

def Otsu_gray2binary(gray):
    image = cv2.imread(gray)
    grayimage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    print(grayimage.shape)
    ret1, th1 = cv2.threshold(grayimage, 0, 255, cv2.THRESH_OTSU)  #方法选择为THRESH_OTSU
    cv2.imwrite("I:/sandstone_binary/" + gray.split("\\")[-1],th1)
    

for filename in filelist:#循环,范围为filelist从1到结束
    filefullpath =os.path.join (path, filename)#os.path.join 函数为路径拼接
    Otsu_gray2binary(filefullpath)#调用裁剪图像的函数

这里套用的还是批量处理的模板,就是自定义函数的最后一句批量命名时和之前不太一样。我误打误撞改成这样可以往下进行了(手动狗头)

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值