将图形中线条或者图案坐标点进行提取

提取图形中坐标点

原理:图像可以用像素表示,像素有RGB值,可以用颜色区分我们需要的图案,然后遍历像素点得到我们需要的坐标点:

测试图形:

代码:

#include <iostream>
#include "opencv.hpp"
#include <highgui/highgui_c.h>
#include <highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>
#include<opencv2/opencv.hpp>
#include<fstream>
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组成一个元组,这样可以通过函数一次性返回
  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值