標籤:source alt 自訂 div stat button bsp 原因 invalid
C#將圖片2值化範例程式碼,原圖及二值化後的圖片如下:
原圖:
二值化後的映像:
實現代碼:
using System;using System.Drawing;namespace BMP2Grey{ class Program { static void ToGrey(Bitmap img1) { for (int i = 0; i < img1.Width; i++) { for (int j = 0; j < img1.Height; j++) { Color pixelColor = img1.GetPixel(i, j); //計算灰階值 int grey = (int)(0.299 * pixelColor.R + 0.587 * pixelColor.G + 0.114 * pixelColor.B); Color newColor = Color.FromArgb(grey, grey, grey); img1.SetPixel(i, j, newColor); } } } static void Thresholding(Bitmap img1) { int[] histogram = new int[256]; int minGrayValue=255, maxGrayValue=0; //求取長條圖 for (int i = 0; i < img1.Width; i++) { for (int j = 0; j < img1.Height; j++) { Color pixelColor = img1.GetPixel(i, j); histogram[pixelColor.R]++; if (pixelColor.R > maxGrayValue) maxGrayValue = pixelColor.R; if (pixelColor.R < minGrayValue) minGrayValue = pixelColor.R; } } //迭代計算閥值 int threshold = -1; int newThreshold = (minGrayValue + maxGrayValue) / 2; for(int iterationTimes = 0; threshold != newThreshold && iterationTimes < 100; iterationTimes++) { threshold = newThreshold; int lP1 =0; int lP2 =0; int lS1 = 0; int lS2 = 0; //求兩個地區的灰階的平均值 for (int i = minGrayValue;i < threshold;i++) { lP1 += histogram[i] * i; lS1 += histogram[i]; } int mean1GrayValue = (lP1 / lS1); for (int i = threshold+1;i < maxGrayValue;i++) { lP2 += histogram[i] * i; lS2 += histogram[i]; } int mean2GrayValue = (lP2 / lS2); newThreshold = (mean1GrayValue + mean2GrayValue) / 2; } //計算二值化 for (int i = 0; i < img1.Width; i++) { for (int j = 0; j < img1.Height; j++) { Color pixelColor = img1.GetPixel(i, j); if (pixelColor.R > threshold) img1.SetPixel(i, j, Color.FromArgb(255, 255, 255)); else img1.SetPixel(i, j, Color.FromArgb(0, 0, 0)); } } } static void Main(string[] args) { try { //開啟位元影像檔案 Bitmap img1 = new Bitmap("test.jpg", true); //灰階化 ToGrey(img1); //二值化 Thresholding(img1); //寫回位元影像檔案 img1.Save("output.jpg"); Console.WriteLine("Converted."); } catch (ArgumentException) { Console.WriteLine("Invalid usage!"); Console.WriteLine("Usage: bmp2grey source object"); } } }}
除聲明外,
跑步客文章均為原創,轉載請以連結形式標明本文地址
c#實現圖片二值化例子(黑白效果)
本文地址: http://www.paobuke.com/develop/c-develop/pbk23670.html
相關內容深入理解C# 裝箱和拆箱(整理篇)ASP.NET C#中Application的用法教程C# web應用程式不能訪問app_code下類的原因以及解決方案C#如何自動識別檔案的編碼
Unity3D擷取當前鍵盤按鍵及Unity3D滑鼠、鍵盤的基本操作C# 擷取漢字的拼音首字母C#自訂匯出資料到Excel的類執行個體C#產生條碼圖片的簡單方法
c#實現圖片二值化例子(黑白效果)