zoukankan      html  css  js  c++  java
  • 挑战图像处理100问(3)——二值化

    在这里插入图片描述
    读取图像,然后将彩色图像进行二值化(Thresholding)。

    二值化是将图像使用黑和白两种颜色表示的方法。

    我们将灰度的阈值设置为128128来进行二值化,即:
    y={0(ify<128)255(else) y= egin{cases} 0& ( ext{if}quad y < 128) \ 255& ( ext{else}) end{cases}
    Author: Tian YJ
    原图如下:

    在这里插入图片描述

    关于二值化

    二值化是图像分割的一种方法。在二值化图象的时候把大于某个临界灰度值的像素灰度设为灰度极大值,把小于这个值的像素灰度设为灰度极小值,从而实现二值化。

    根据阈值选取的不同,二值化的算法分为固定阈值和自适应阈值。 比较常用的二值化方法则有:双峰法、P参数法、迭代法和OTSU法等。

    # -*- coding: utf-8 -*-
    """
    Created on Tue Apr  7 16:23:59 2020
    
    @author: Tian YJ
    """
    
    import numpy as np
    import cv2
    
    # 灰度化函数
    def BGR2GRAY(img):
    
    	# 获取图片尺寸
    	H, W, C = img.shape
    
    	# 灰度化
    	out = np.ones((H,W,3))
    	for i in range(H):
    		for j in range(W):
    			out[i,j,:] = 0.299*img[i,j,0] + 0.578*img[i,j,1] + 0.114*img[i,j,2]
    
    	out = out.astype(np.uint8)
    
    	return out
    
    # 二值化函数
    def binarization(img, th=128):
    	img[img < th] = 0
    	img[img >= th] = 255
    	return img
    
    # 读取图片
    path = 'C:/Users/86187/Desktop/image/'
    
    
    file_in = path + 'cake.jpg' 
    file_out = path + 'binarization.jpg' 
    img = cv2.imread(file_in)
    
    # 调用函数
    out = BGR2GRAY(img)
    out = binarization(out)
    
    # 保存图片
    cv2.imwrite(file_out, out)
    cv2.imshow("result", out)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
    

    在这里插入图片描述

  • 相关阅读:
    SP1716 GSS3
    A Simple Problem with Integers题解
    P4528 [CTSC2008]图腾 题解
    P1498 南蛮图腾 题解
    P2024 [NOI2001]食物链 题解
    Windows编程 Windows程序的生与死(中)
    Windows编程 Windows程序的生与死(上)
    C#实现在注册表中保存信息
    沿路径动画(Animation Along a Path)
    倾斜动画(SkewTransform)
  • 原文地址:https://www.cnblogs.com/Jack-Tim-TYJ/p/12831925.html
Copyright © 2011-2022 走看看