Skip to content

Instantly share code, notes, and snippets.

@amroamroamro
Created February 1, 2015 19:52
Show Gist options
  • Save amroamroamro/14fcc404ec3ed8f4e196 to your computer and use it in GitHub Desktop.
Save amroamroamro/14fcc404ec3ed8f4e196 to your computer and use it in GitHub Desktop.
[mexopencv] Epipolar Geometry example
function example_epipolar_geometry
% a pair of stereo images (grayscale)
img1 = cv.imread('left.jpg', 'Flags',0);
img2 = cv.imread('right.jpg', 'Flags',0);
% detect keypoints and calculate descriptors using SIFT
[key1,feat1] = cv.SIFT(img1);
[key2,feat2] = cv.SIFT(img2);
% match descriptors using FLANN
matcher = cv.DescriptorMatcher('FlannBased', ...
'Index',{'KDTree', 'Trees',5}, 'Search',{'Checks',50});
m = matcher.knnMatch(feat1, feat2, 2);
m = cat(1, m{:}); % N-by-2 array of structs
% keep only "good" matches (using ratio test as per Lowe's paper)
idx_good = ([m(:,1).distance] < 0.8*[m(:,2).distance]);
m = m(idx_good,1);
% extract keypoints from filtered matches
% (0-based vs. 1-based indexing in C++/MATLAB)
pts1 = num2cell(cat(1, key1([m.queryIdx]+1).pt), 2);
pts2 = num2cell(cat(1, key2([m.trainIdx]+1).pt), 2);
% find Fundamental matrix
[F,mask] = cv.findFundamentalMat(pts1, pts2, 'Method','LMedS');
mask = logical(mask);
% select only inlier points
pts1 = pts1(mask);
pts2 = pts2(mask);
% find epilines, and draw them in corresponding images
lines1 = cv.computeCorrespondEpilines(pts2, F, 'WhichImage',2);
lines2 = cv.computeCorrespondEpilines(pts1, F, 'WhichImage',1);
[img11,~] = drawlines(img1, img2, lines1, pts1, pts2);
[img22,~] = drawlines(img2, img1, lines2, pts2, pts1);
% result
figure('Position',[200 200 1200 400])
subplot(121), imshow(img11)
subplot(122), imshow(img22)
end
function [img1,img2] = drawlines(img1, img2, lines, pts1, pts2)
c = size(img1,2);
img1 = cv.cvtColor(img1, 'GRAY2RGB');
img2 = cv.cvtColor(img2, 'GRAY2RGB');
for i=1:numel(lines)
clr = randi([0 255], [1 3], 'uint8');
r = lines{i};
p1 = uint32([0, -r(3)/r(2)]);
p2 = uint32([c, -(r(3)+r(1)*c)/r(2)]);
img1 = cv.line(img1, p1, p2, 'Color',clr, 'LineType','AA');
img1 = cv.circle(img1, pts1{i}, 5, 'Color',clr, 'Thickness',-1);
img2 = cv.circle(img2, pts2{i}, 5, 'Color',clr, 'Thickness',-1);
end
end
@candemiroguz
Copy link

I have a problem about that codes.I've error using imread failed.Could you help me please?

@candemiroguz
Copy link

Error using imread
imread failed

Error in example_epipolar_geometry (line 3)
img1 =cv.imread('left.tif', 'Flags',0);

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