Ask Your Question

Revision history [back]

You can remove n last rows of a matrix (image) by using the constructor of Mat class. In the same way, after generating a transformation matrix, you can remove n last columns. See the code below for gray scale images:

// Remove n last rows or columns
#include <iostream>
#include <opencv2/imgproc.hpp> // for cvtColor
#include <opencv2/highgui.hpp> // for imshow
#include <opencv2/core.hpp> // for core OpenCV components

using namespace std;
using namespace cv;
// run: <program> <image path> <0:remove rows, 1: remove columns> <n>

int main(int argc, char * argv[])
{
    Mat im = imread(argv[1]); // read input image
    int choose = atoi(argv[2]); // choose = 0 means removing row, others mean removing column
    int n = atoi(argv[3]); // number of rows or columns to remove
    if (im.channels() > 0)
        cvtColor(im, im, CV_RGB2GRAY);
    cout << "Rows:" << im.rows << endl;
    cout << "Cols:" << im.cols << endl;
    if (0!=choose) // columns remove
        im = im.t();
    Mat im2 = Mat(im.rows-n, im.cols, CV_8UC1, im.data);
    if (0 != choose) // columns remove
    { 
        im2 = im2.t();
        im = im.t(); //covert back to original
    }


    cout << "Rows:" << im2.rows << endl;
    cout << "Cols:" << im2.cols << endl;
    imshow("Original image", im);
    imshow("Result image", im2);
    cvWaitKey(0);
    return 0;
}

You can remove n last rows of a matrix (image) by using the constructor of Mat class. In the same way, after generating a transformation matrix, you can remove n last columns. See the code below for gray scale images:

// Remove n last rows or columns
#include <iostream>
#include <opencv2/imgproc.hpp> // for cvtColor
#include <opencv2/highgui.hpp> // for imshow
#include <opencv2/core.hpp> // for core OpenCV components

using namespace std;
using namespace cv;
// run: <program> <image path> <0:remove rows, 1: remove columns> <n>

int main(int argc, char * argv[])
{
    Mat im = imread(argv[1]); // read input image
    int choose = atoi(argv[2]); // choose = 0 means removing row, others mean removing column
    int n = atoi(argv[3]); // number of rows or columns to remove
    if (im.channels() > 0)
        cvtColor(im, im, CV_RGB2GRAY);
    cout << "Rows:" << im.rows << endl;
    cout << "Cols:" << im.cols << endl;
    if (0!=choose) // for columns remove
remove, transform original image to its transformed form
        im = im.t();
    Mat im2 = Mat(im.rows-n, im.cols, CV_8UC1, im.data);
    if (0 != choose) // for columns remove
remove, converting result and im to their correct forms
    { 
        im2 = im2.t();
        im = im.t(); //covert back to original
    }


    cout << "Rows:" << im2.rows << endl;
    cout << "Cols:" << im2.cols << endl;
    imshow("Original image", im);
    imshow("Result image", im2);
    cvWaitKey(0);
    return 0;
}