栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

图像阈值分割代码模板

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

图像阈值分割代码模板

一、手工阈值分割

代码部分:

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)#调用裁剪图像的函数

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/275961.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号