常用代码片段

本文最后更新于 2025-11-16 22:15:19

Byte[]转灰度图
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public static Bitmap ByteToGrayBitmap(byte[] imageBuffer, int imageWidth, int imageHeight)
{
Bitmap bmp = new Bitmap(imageWidth, imageHeight, PixelFormat.Format8bppIndexed);
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, imageWidth, imageHeight),
ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
unsafe
{
fixed (byte* image = imageBuffer)
{
for (int y = 0; y < imageHeight; y++)
{
byte* src = image + imageWidth * y;
byte* dst = (byte*)bmpData.Scan0 + bmpData.Stride * y;
Buffer.MemoryCopy(src, dst, imageWidth, imageWidth);
}
}
}

bmp.UnlockBits(bmpData);

ColorPalette tempPalette;
using (Bitmap tempBmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
{
tempPalette = tempBmp.Palette;
}
for (int i = 0; i < 256; i++)
{
tempPalette.Entries[i] = Color.FromArgb(i, i, i);
}
bmp.Palette = tempPalette;
return bmp;
}
Byte[]转彩色图
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static Bitmap ByteToBitmap(byte[] imageBuffer, int imageWidth, int imageHeight)
{
Bitmap bmp = new Bitmap(imageWidth, imageHeight, PixelFormat.Format24bppRgb);
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, imageWidth, imageHeight),
ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
unsafe
{
fixed (byte* image = imageBuffer)
{
for (int y = 0; y < imageHeight; y++)
{
byte* src = image + imageWidth * 3 * y;
byte* dst = (byte*)bmpData.Scan0 + bmpData.Stride * y;
Buffer.MemoryCopy(src, dst, imageWidth * 3, imageWidth * 3);
}
}
}

bmp.UnlockBits(bmpData);
return bmp;
}
PictureBox双缓存
1
2
3
4
5
6
7
8
9
private void SetDoubleBuffering()
{
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.UpdateStyles();
}
c++ INIHelper
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#pragma once

#ifndef IniHelper_H
#define IniHelper_H

#include <Windows.h>
#include <string>
#include <atlstr.h>
#include <io.h>

class IniHelper
{
private:
static LPCTSTR CharToLPCTSTR(const char* value);
static std::string GetStringA(const char* key, std::string def_val = "");
static void WriteStringA(const char* key, std::string value);

public:
static void SetFileName(const char* fileName);
static void SetSection(const char* section);

static int GetInt(const char* key, int def_val = 0);
static void WriteInt(const char* key, int value);

static bool GetBool(const char* key, bool def_val = false);
static void WriteBool(const char* key, bool value);

static double GetDouble(const char* key, double def_val = 0.0);
static void WriteDouble(const char* key, double value);

static CString GetString(const char* key, std::string def_val = "");
static void WriteString(const char* key, CString value);
};

CHAR FileName[MAXBYTE];
CHAR Section[MAXBYTE];

inline LPCTSTR IniHelper::CharToLPCTSTR(const char* value)
{
int num = MultiByteToWideChar(0, 0, value, -1, NULL, 0);
wchar_t* wide = new wchar_t[num];
MultiByteToWideChar(0, 0, value, -1, wide, num);
return wide;
}
inline std::string IniHelper::GetStringA(const char* key, std::string def_val)
{
CHAR cTmp[MAXBYTE];
memset(cTmp, 0, sizeof(cTmp));
GetPrivateProfileStringA(Section, key, def_val.c_str(), cTmp, MAXBYTE, FileName);
return cTmp;
}
inline void IniHelper::WriteStringA(const char* key, std::string value)
{
WritePrivateProfileStringA(Section, key, value.c_str(), FileName);
}


inline void IniHelper::SetFileName(const char* fileName)
{
memset(FileName, 0, sizeof(FileName));
memcpy(FileName, fileName, strlen(fileName) + 1);
}
inline void IniHelper::SetSection(const char* section)
{
memset(Section, 0, sizeof(Section));
memcpy(Section, section, strlen(section) + 1);
}


inline int IniHelper::GetInt(const char* key, int def_val)
{
return GetPrivateProfileInt(CharToLPCTSTR(Section),
CharToLPCTSTR(key), def_val,
CharToLPCTSTR(FileName));
}
inline void IniHelper::WriteInt(const char* key, int value)
{
WriteStringA(key, std::to_string(value).c_str());
}


inline bool IniHelper::GetBool(const char* key, bool def_val)
{
return GetStringA(key, def_val ? "True" : "False") == "True";
}
inline void IniHelper::WriteBool(const char* key, bool value)
{
WriteStringA(key, value ? "True" : "False");
}


inline double IniHelper::GetDouble(const char* key, double def_val)
{
return atof(GetStringA(key, std::to_string(def_val).c_str()).c_str());
}
inline void IniHelper::WriteDouble(const char* key, double value)
{
WriteStringA(key, std::to_string(value).c_str());
}


inline CString IniHelper::GetString(const char* key, std::string def_val)
{
TCHAR cTmp[MAXBYTE];
memset(cTmp, 0, sizeof(cTmp));
GetPrivateProfileString(CharToLPCTSTR(Section),
CharToLPCTSTR(key),
CharToLPCTSTR(def_val.c_str()), cTmp, MAXBYTE,
CharToLPCTSTR(FileName));
return cTmp;
}
inline void IniHelper::WriteString(const char* key, CString value)
{
if (_access(FileName, 0))
{
FILE* pFile(NULL);
if (_wfopen_s(&pFile, CharToLPCTSTR(FileName), L"wt, ccs=UNICODE") == 0)
fclose(pFile);
}

WritePrivateProfileString(CharToLPCTSTR(Section),
CharToLPCTSTR(key),
value,
CharToLPCTSTR(FileName));
}

#endif // !IniHelper_H
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "IniHelper.h"

int main()
{
IniHelper::SetFileName("D:\\1.ini");
IniHelper::SetSection("Default");
auto test1 = IniHelper::GetString("Test1");
auto test2 = IniHelper::GetString("Test2");
auto test3 = IniHelper::GetString("Test3");
auto test4 = IniHelper::GetInt("Test4");
auto test5 = IniHelper::GetDouble("Test5");
auto test6 = IniHelper::GetBool("Test6");

IniHelper::SetFileName("D:\\test3.ini");
IniHelper::SetSection("Default");
IniHelper::WriteString("Test1", test1);
IniHelper::WriteString("Test2", test2);
IniHelper::WriteString("Test3", test3);
IniHelper::WriteInt("Test4", test4);
IniHelper::WriteDouble("Test5", test5);
IniHelper::WriteBool("Test6", test6);

return 0;
}
OTSU算法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
int OTSU(Mat& src)
{
int hist[UCHAR_MAX + 1]{ 0 };
float histPro[UCHAR_MAX + 1]{ 0 };
int height = src.rows;
int width = src.cols;
int channel = src.channels();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (channel == 1)
{
hist[src.at<uchar>(y, x)]++;
}
else if (channel == 3)
{
hist[src.at<Vec3b>(y, x)[0]]++;
hist[src.at<Vec3b>(y, x)[1]]++;
hist[src.at<Vec3b>(y, x)[2]]++;
}
}
}
long sum = height * width * channel;
for (int i = 0; i < UCHAR_MAX + 1; i++)
{
histPro[i] = hist[i] * 1.0 / sum;
}

double avgValue = 0;
for (int i = 0; i < UCHAR_MAX + 1; i++)
{
avgValue += i * histPro[i];
}

int index = 0;
double w0 = 0.0, w1 = 1.0;
double u0 = 0.0, u1 = avgValue;
double u0tmp = 0.0, u1tmp = 0.0;
double max_g = 0.0;
for (int i = 0; i < UCHAR_MAX + 1; i++)
{
w0 += histPro[i];
w1 = 1 - w0;

u0tmp += i * histPro[i];
u1tmp = avgValue - u0tmp;

u0 = u0tmp / w0;
u1 = u1tmp / w1;

double g = w0 * w1 * (u0 - u1) * (u0 - u1);
if (g > max_g)
{
max_g = g;
index = i;
}
}
return index;
}

OpenCV

unsigned char* to Mat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
cv::Mat src;
if (image_channel == 1)
{
src = cv::Mat(cv::Size(image_width, image_height), CV_8UC1);
memcpy(src.data, in_data, image_width * image_height * image_channel);
}
else if (image_channel == 3)
{
src = cv::Mat(cv::Size(image_width, image_height), CV_8UC3);
memcpy(src.data, in_data, image_width * image_height * image_channel);
}
else if (image_channel == 4)
{
src = cv::Mat(cv::Size(image_width, image_height), CV_8UC4);
memcpy(src.data, in_data, image_width * image_height * image_channel);
}
Mat to unsigned char*
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
cv::Mat dst; ///以在其它地方赋值
if (dst.isContinuous())
{
memcpy(out_data, dst.data, image_width * image_height * image_channel);
}
else
{
for (int h = 0; h < image_height; h++)
{
uchar *p = dst.ptr<uchar>(h);
for (int w = 0; w < image_width; w++)
{
for (int c = 0; c < image_channel; c++)
{
out_data[w * image_channel + c] = p[w * image_channel + c];
}
}
}
}
calcHist
1
2
3
4
5
6
7
8
9
10
11
12
cv::Mat hist;
const int histSize[] = { 256 };
float pranges[] = { 0,256 };
const float* ranges[] = { pranges };

cv::calcHist(&src, 1, 0, cv::Mat(), hist, 1, histSize, ranges);

float *p = hist.ptr<float>(0);
for (int y = 0; y <= UCHAR_MAX; y++)
{
/// p[y] 遍历hist
}
HObject 与 Mat互转
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
cv::Mat HObject2Mat(HObject& ho_Image)
{
cv::Mat img;
HTuple hv_Channels;

ConvertImageType(ho_Image, &ho_Image, "byte");
CountChannels(ho_Image, &hv_Channels);
if (hv_Channels.I() == 1)
{
HTuple hv_Ptr, hv_Type, hv_Width, hv_Height;
GetImagePointer1(ho_Image, &hv_Ptr, &hv_Type, &hv_Width, &hv_Height);

img = cv::Mat(cv::Size(hv_Width, hv_Height), CV_8UC1);
unsigned char* pdata = (unsigned char*)hv_Ptr.L();
memcpy(img.data, pdata, hv_Width.I() * hv_Height.I());
}
else if (hv_Channels.I() == 3)
{
HTuple hv_PtrR, hv_PtrG, hv_PtrB, hv_Type, hv_Width, hv_Height;
GetImagePointer3(ho_Image, &hv_PtrR, &hv_PtrG, &hv_PtrB, &hv_Type, &hv_Width, &hv_Height);

img = cv::Mat(cv::Size(hv_Width, hv_Height), CV_8UC3);

std::vector<cv::Mat> vecM(3);
vecM[0] = cv::Mat(cv::Size(hv_Width, hv_Height), CV_8UC1);
vecM[1] = cv::Mat(cv::Size(hv_Width, hv_Height), CV_8UC1);
vecM[2] = cv::Mat(cv::Size(hv_Width, hv_Height), CV_8UC1);
unsigned char* R = (unsigned char*)hv_PtrR.L();
unsigned char* G = (unsigned char*)hv_PtrG.L();
unsigned char* B = (unsigned char*)hv_PtrB.L();
memcpy(vecM[2].data, R, hv_Width.I() * hv_Height.I());
memcpy(vecM[1].data, G, hv_Width.I() * hv_Height.I());
memcpy(vecM[0].data, B, hv_Width.I() * hv_Height.I());
cv::merge(vecM, img);
}
return img;
}

HObject Mat2HObject(cv::Mat& img)
{
HObject ho_Image;
if (img.channels() == 4)
{
cv::cvtColor(img, img, cv::COLOR_BGRA2BGR);
}
if (img.channels() == 1)
{
GenImage1(&ho_Image, "byte", img.cols, img.rows, (Hlong)img.data);
}
else if (img.channels() == 3)
{
std::vector<cv::Mat> vecM;
cv::split(img, vecM);
cv::Mat imgB = vecM[0];
cv::Mat imgG = vecM[1];
cv::Mat imgR = vecM[2];
GenImage3(&ho_Image, "byte", img.cols, img.rows, (Hlong)imgR.data, (Hlong)imgG.data, (Hlong)imgB.data);
}

return ho_Image;
}

常用代码片段
https://njit-77.github.io/2022/01/13/常用代码片段/
作者
njit-77
发布于
2022年1月13日
许可协议