更新
鉴于您对行数和最大 x,y 尺寸的回复,我在此答案底部的基于 ImageMagick 的原始方法显然不适合您的特定问题。但是,我会把它留给其他人看,因为它最多可以容纳几十行。我现在提供一个更合适的gnuplot 版本。
Gnuplot 版本
如果你想用gnuplot 来做,它看起来像这样:
set terminal png size 1000,1000
set output 'result.png'
unset xtics
unset ytics
unset border
plot 'lines.txt' using 1:2:($3-$1):($4-$2) with vectors nohead notitle
如果您将其保存在名为 plot.cmd 的文件中,则可以使用以下命令运行它
gnuplot < plot.cmd
如果您想要箭头,请使用如下变体:
set terminal png size 1000,1000
set output 'result.png'
set style arrow 1 heads filled size screen 0.03,15,45 ls 1
unset xtics
unset ytics
unset border
plot 'lines.txt' using 1:2:($3-$1):($4-$2) with vectors arrowstyle 1 notitle
Magick++ 和 C++ 答案
我决定想出一个 Magick++ 和 C++ 的答案,只是为了好玩。代码如下所示 - 编译命令显示在顶部的 cmets 中。
////////////////////////////////////////////////////////////////////////////////
// sample.cpp
// Mark Setchell
//
// ImageMagick Magick++ sample code
//
// Compile with:
// g++ sample.cpp -o sample $(Magick++-config --cppflags --cxxflags --ldflags --libs)
////////////////////////////////////////////////////////////////////////////////
#include <Magick++.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
using namespace Magick;
int main(int argc,char **argv)
{
InitializeMagick(*argv);
// Create an image object, scaled by a factor of 100 to speed it up !
float scale=100.0;
Image image("650x650","white");
// Construct drawing list
std::list<Magick::Drawable> drawList;
// Initial settings, blue lines 1 pixel thick
drawList.push_back(DrawableStrokeColor("blue"));
drawList.push_back(DrawableStrokeWidth(1));
// Read in lines from file, expected format "x1 y1 x2 y2"
int lineno=0;
std::ifstream infile("lines.txt");
std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
int x1,y1,x2,y2;
iss >> x1;
iss >> y1;
iss >> x2;
iss >> y2;
x1 = int(x1/scale);
y1 = int(x2/scale);
x2 = int(y1/scale);
y2 = int(y2/scale);
cout << "Line: " << ++lineno << " " << x1 << "," << y1 << " " << x2 << "," << y2 << endl;
// Add this point to the list of lines to draw
drawList.push_back(DrawableLine(x1,y1,x2,y2));
}
// Draw everything using completed drawing list
image.draw(drawList);
// Write the image to a file
image.write( "result.png" );
return 0;
}
我用 Perl 生成了 1000 行随机测试数据,如下所示:
perl -E 'for($i=0;$i<1000;$i++){printf("%d %d %d %d\n",int rand 65000,int rand 65000, int rand 65000, int rand 65000);}' > lines.txt
结果如下:
原答案
您也可以使用已经安装在大多数 Linux 发行版上的 ImageMagick 轻松完成。下面其实只有4行代码——剩下的都是cmets:
#!/bin/bash
# Create the output image, 1000x1000 pixels say
convert -size 1000x1000 xc:pink result.png
# Suppressing lines that have a hash (#) at the start, read in the file "lines.txt"
grep -v "^#" lines.txt | while read x1 y1 x2 y2; do
echo Read line $x1,$y1 $x2,$y2
# Tell ImageMagick to draw the line on the image
convert result.png -stroke blue -strokewidth 5 -draw "line $x1,$y1 $x2,$y2" result.png
done
输出
Read line 123,567 798,900
Read line 788,900 87,89