Skip to content

Instantly share code, notes, and snippets.

@shimondoodkin
Forked from enpe/main.cpp
Last active October 10, 2020 20:13
Show Gist options
  • Save shimondoodkin/9ce104e83da58e1142f16ac36a909097 to your computer and use it in GitHub Desktop.
Save shimondoodkin/9ce104e83da58e1142f16ac36a909097 to your computer and use it in GitHub Desktop.
Deleting N rows (or columns) from cv::Mat.
void MatRemoveRows(cv::Mat& matIn, int row, int rowCount=1)
{
cv::Size size = matIn.size();
cv::Mat matOut(size.height - rowCount, size.width, matIn.type());
if (!(matIn.isContinuous() && matOut.isContinuous())) throw "both should be continous"; //fix later if required, maybe use the rect solution if not continious https://gist.github.com/enpe/369a7a17fd9b3856b544 OR use as https://kezunlin.me/post/61d55ab4/
int rowSizeInBytes = size.width * sizeof(matIn.elemSize());
if (row > 0)
{
int numRows = row;
int numBytes = rowSizeInBytes * numRows;
// copy to before row, from 0
std::memcpy(matOut.data, matIn.data, numBytes);
}
if (row < size.height - 1)
{
// copy rest after rows
int matOutOffset = rowSizeInBytes * row; // start copy to position
int matInOffset = matOutOffset + (rowSizeInBytes* rowCount); // start copy from position
int numRows = size.height - (row + rowCount); //cout of rest rows
int numBytes = rowSizeInBytes * numRows;
std::memcpy(matOut.data + matOutOffset, matIn.data + matInOffset, numBytes);
}
matIn = matOut;
}
void MatRemoveCols(cv::Mat& matIn, int col, int colCount = 1)
{
cv::Size size = matIn.size();
cv::Mat matOut(size.height, size.width - colCount, (int)matIn.elemSize());
if (!(matIn.isContinuous() && matOut.isContinuous())) throw "both should be continous"; //fix later if required, maybe use the rect solution if not continious https://gist.github.com/enpe/369a7a17fd9b3856b544 OR use as https://kezunlin.me/post/61d55ab4/
int rowInInBytes = size.width * ((int)matIn.elemSize());
int rowOutInBytes = (size.width - colCount) * ((int)matIn.elemSize());
if (col > 0)
{
int matInOffset = 0;
int matOutOffset = 0;
int numCols = col;
int numBytes = numCols * ((int)matIn.elemSize());
for (int y = 0; y < size.height; ++y)
{
std::memcpy(matOut.data + matOutOffset, matIn.data + matInOffset, numBytes);
matInOffset += rowInInBytes;
matOutOffset += rowOutInBytes;
}
}
if (col < size.width - 1)
{
int matInOffset = (col + colCount) * ((int)matIn.elemSize());
int matOutOffset = col * ((int)matIn.elemSize());
int numCols = size.width - (col + colCount);
int numBytes = numCols * ((int)matIn.elemSize());
for (int y = 0; y < size.height; ++y)
{
std::memcpy(matOut.data + matOutOffset, matIn.data + matInOffset, numBytes);
matInOffset += rowInInBytes;
matOutOffset += rowOutInBytes;
}
}
matIn = matOut;
}
@shimondoodkin
Copy link
Author

shimondoodkin commented Oct 9, 2020

code not well tested yet, it compiles.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment