Skip to content

Instantly share code, notes, and snippets.

@kazuki-ma
Created February 22, 2012 23:13
Show Gist options
  • Save kazuki-ma/1888265 to your computer and use it in GitHub Desktop.
Save kazuki-ma/1888265 to your computer and use it in GitHub Desktop.
パディングを回避する
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
// カスタムアロケータ
namespace cvut
{
template<int alignment_bytes>
class customAllocator: public cv::MatAllocator
{
public:
customAllocator () {}
virtual ~customAllocator() {}
void allocate(int dims, const int* sizes, int type, int*& refcount,
uchar*& datastart, uchar*& data, size_t* step)
{
// latest step is always equals with element size.
// e.g. step[1] == 24 when matrix is 2-d CV_8UC3.
step[dims-1] = CV_ELEM_SIZE(type);
// calculate each step[x] from bottom to top.
// cv::alignSize is effective when step[dims - 2].
for(int d = dims - 2; d >= 0; --d) {
step[d] = cv::alignSize(step[d+1] * sizes[d], alignment_bytes);
}
// total needed size of new allocation
const size_t total
= cv::alignSize(sizeof(size_t), alignment_bytes)
+ cv::alignSize(step[0] * sizes[0], alignment_bytes);
// allocate new memory region and save the its pointer.
uint8_t* const allocated_pointer = reinterpret_cast<uint8_t*>(cv::fastMalloc(total));
refcount = reinterpret_cast<int*>(allocated_pointer);
data = datastart = reinterpret_cast<uint8_t*>
(allocated_pointer + cv::alignSize(sizeof(size_t), alignment_bytes));
// set to refcount is 1 because its allocated now and its reference is 1
// until this method.
*refcount = 1;
}
// deallocate
void deallocate(int* refcount, uchar* datastart, uchar* data)
{
if (!refcount) return; // allocated by user
else cv::fastFree(refcount); // allocated by its allocator
}
};
customAllocator<4> allocator_gl;
}
int
main(int argc, char *argv[])
{
cv::Mat src_mat(333, 333, CV_8UC3);// = cv::imread("../../image/lenna333x333.png", 1);
if(src_mat.empty()) return -1;
int cols = 333, rows = 333;
// カスタムアロケータを使用する
cv::Mat dst_mat;
dst_mat.allocator = &cvut::allocator_gl;
src_mat.copyTo(dst_mat);
std::cout << "src_mat" << std::endl;
std::cout << " size=(" << src_mat.cols << ", " << src_mat.rows << ")" << std::endl;
std::cout << " step=" << src_mat.step << std::endl;
std::cout << " isContinuous:" << (src_mat.isContinuous()?"true":"false") << std::endl;
std::cout << " isSubmatrix=" << (src_mat.isSubmatrix()?"true":"false") << std::endl;
std::cout << "dst_mat" << std::endl;
std::cout << " size=(" << dst_mat.cols << ", " << dst_mat.rows << ")" << std::endl;
std::cout << " step=" << dst_mat.step << std::endl;
std::cout << " isContinuous=" << (dst_mat.isContinuous()?"true":"false") << std::endl;
std::cout << " isSubmatrix=" << (dst_mat.isSubmatrix()?"true":"false") << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment