Skip to content

Instantly share code, notes, and snippets.

@mattak
Created August 20, 2013 10:55
Show Gist options
  • Save mattak/6280006 to your computer and use it in GitHub Desktop.
Save mattak/6280006 to your computer and use it in GitHub Desktop.
image concatenate
//
// imcon
// image concatenater
// usage:
// imcon [img]+
//
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <boost/regex.hpp>
using namespace cv;
using namespace std;
void
usage(char *cmd) {
cerr << "[usage] " << cmd << " [images]+" << endl;
}
void
show_wait(Mat img) {
namedWindow("name", CV_WINDOW_AUTOSIZE);
imshow("name", img);
waitKey(0);
}
string
normalize_filestr(const char *chrs) {
string str = chrs;
boost::regex re("[0-9]+");
string result = boost::regex_replace(str, re, "");
cout << result << endl;
return result;
}
Mat
create_mask(Mat img) {
Mat mask(Size(img.cols, img.rows), CV_8UC1);
int ch = img.channels();
for (int y=0; y<img.rows; y++) {
for (int x=0; x<img.cols; x++) {
int a = img.step * y + x * ch;
int b = mask.step * y + x;
if ( img.data[a+0] == 0
&& img.data[a+1] == 0
&& img.data[a+2] == 0) {
mask.data[b] = 0;
}
else {
mask.data[b] = 255;
}
}
}
return mask;
}
Mat
add_channel(Mat img) {
vector<Mat> channels;
split(img, channels);
Mat mask = create_mask(img);
channels.push_back(mask);
Mat bgra;
merge(channels, bgra);
return bgra;
}
int
main(int argc, char** argv) {
// argument check
if (argc <= 1) {
usage(argv[0]);
return 1;
}
// measure
vector<Mat> list;
int total_width = 0;
int max_height = 0;
for (int i=1; i<argc; i++) {
cout << "[load] " << argv[i] << endl;
list.push_back(imread(argv[i]));
Mat last = list.back();
if (last.empty()) {
cout << "empty image: " << argv[i] << endl;
return 1;
}
total_width += last.cols;
max_height = max(max_height, last.rows);
}
cout << "[total_width] " << total_width << endl;
cout << "[max_height] " << max_height << endl;
// joint
Mat combined(Size(total_width, max_height), CV_8UC3);
vector<Mat>::iterator it = list.begin();
vector<Mat>::iterator it_end = list.end();
Rect roi_rect;
while (it != it_end) {
roi_rect.width = it->cols;
roi_rect.height = it->rows;
Mat roi(combined, roi_rect);
it->copyTo(roi);
roi_rect.x += it->cols;
++it;
}
// 3channel -> 4channel
Mat merged = add_channel(combined);
// write
string filestr = argv[1];
string newstr = normalize_filestr(argv[1]);
imwrite(newstr.c_str(), merged);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment