原理:图像可以用像素表示,像素有RGB值,可以用颜色区分我们需要的图案,然后遍历像素点得到我们需要的坐标点:
代码:
#include
#include "opencv.hpp"
#include
#include
#include
#include
#include
using namespace cv;
using namespace std;
int main()
{
IplImage* img = cvLoadImage("E:\\opencv\\test\\test.jpg", CV_LOAD_IMAGE_COLOR);
uchar* data = (uchar*)img->imageData;
int step = img->widthStep / sizeof(uchar);
int channels = img->nChannels;
int R, G, B;
ofstream fout;
fout.open("test.txt", ios::out);
for (int i = 0; i < img->height; i++)
{
for (int j = 0; j < img->width; j++)
{
B = (int)data[i * step + j * channels + 0];
G = (int)data[i * step + j * channels + 1];
R = (int)data[i * step + j * channels + 2];
if (R!=0 && G!=0 && B!=0)
{
fout << i << ", " << j << endl;
}
//fout << "( " << i << ", " << j << " ) = ( " << R << "," << G << "," << B << ")" << endl;
//同时输出RGB值,我们不需要,只需要坐标点
}
}
fout.close();
return 0;
}
输出结果保存于test.txt中:
对输出的点进行验证:
我们使用python中绘图的库进行验证,python画图比较好用。
代码如下:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'NSimSun,Times New Roman'
x, y = np.loadtxt('pt1.txt', delimiter=',', unpack=True)
plt.plot(x, y, '*', label='Data', color='black')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Data')
plt.legend()
plt.show()
不知道CSDN这个图片怎么旋转,传上来转了角度。。。
附上python中通过TXT文件绘图的代码,可能以后用到:
文件格式对应的还是之前的中间有逗号的二维坐标点,代码如下,能够拟合,给点能够拟合成线的那种,上边那个是仅标出带你不处理,注意区别:
import matplotlib.pyplot as plt
with open('pt1.txt', 'r') as f:
X, Y = zip(*[[float(s) for s in line.split(',')] for line in f])
plt.plot(X, Y)
plt.show()
或者:
import matplotlib.pyplot as plt
filename = 'pt0.txt'
X, Y = [], []
with open(filename, 'r') as f: # 1
lines = f.readlines() # 2
for line in lines: # 3
value = [float(s) for s in line.split(',')] # 4
X.append(value[0]) # 5
Y.append(value[1])
print(X)
print(Y)
plt.plot(X, Y)
plt.show()
或者:
import pylab
def loadData(flieName):
inFile = open(flieName, 'r')#以只读方式打开某fileName文件
#定义两个空list,用来存放文件中的数据
X = []
y = []
for line in inFile:
trainingSet = line.split(',') #对于每一行,按','把数据分开,这里是分成两部分
X.append(trainingSet[0]) #第一部分,即文件中的第一列数据逐一添加到list X 中
y.append(trainingSet[1]) #第二部分,即文件中的第二列数据逐一添加到list y 中
return (X, y) # X,y组成一个元组,这样可以通过函数一次性返回