Thursday, September 29, 2011

Crop picture using gnuplot

We talked about converting a rgb image to a gray one using gnuplot last time. Except this, Gnuplot also can do some other manipulations such as cropping, rotating and so on. In this article and next few ones I will talk about them respectively. This time we deal with cropping.

Cropping is selecting specific area from the picture, then drawing it to an output file. In gnuplot this can be done by setting the xrange and yrnage to a proper value and then plot. The script is shown below.
#Utility: crop png pictures using gnuplot.
#Author:数声风笛离亭晚,我想潇湘君想秦!
#Email:qinjieli@gmail.com
#Usage:
##call "crop.gnuplot" x1 y1 x2 y2 inputfile outputfile
#parameters:
##x1: x-value of left-bottom point
##y1: y-value of left-bottom point
##x2: x-value of right-top point
##y2: y-value of right-top point
##inputfile: input filename (without ".png")
##outputfile: output filename (without ".png")
reset
x1="$0"   #The left bottom point
y1="$1"
x2="$2"   #The right top point
y2="$3"
inputfile="$4.png"    #inputfile name
outputfile="$5.png"   #outputfile name
set xrange [x1:x2]
set yrange [y1:y2]
set size ratio -1
# Set the scales so that the unit has the same length
#on both the x and y axes
#There shold be no margin
set lmargin 0
set rmargin 0
set tmargin 0
set bmargin 0
#There shold be no key tics and border
unset key
unset tics
unset border
set term png truecolor size (x2-x1),(y2-y1)
set output outputfile
plot inputfile binary filetype=png w rgbimage
Save this script as "crop.gnuplot". Then it can be called from gnuplot like this:
gnuplot> call "crop.gnuplot" x1 y1 x2 y2 inputfile outputfile
In the end as usual let me show a finished work.

Input picture file (initial file download from here)

Picture cropped using command "call "plot.gplt" 250 150 500 400 input output"

1 comment:

  1. Nice blog. Thanx for the example scripts.

    ReplyDelete

Creative Commons License
Except as otherwise noted, the content of this page is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.