function mat = cvreal2d_to_mat(cv)
# Read2D 型を要素とする配列（OpenCV のデータ）cv を，Octave の2次元配列 mat にコピー
for x = [1:cv.width] 
  for y = [1:cv.height] 
    mat(y,x) = cvGetReal2D(cv, y-1, x-1);
  end
end
endfunction 

function cv = mat_to_cvreal2d(mat)
# Octave の2次元配列 mat を，Read2D 型を要素とする配列（OpenCV のデータ）cv にコピー
height = size(mat)(1); 
width = size(mat)(2); 
for x = [1:width] 
  for y = [1:height] 
    cvSetReal2D(cv, y-1, x-1, mat(y,x));
  end
end
endfunction 

# motion vector
# read and convert to grayscale image
img1 = cvLoadImage("20090701001_avi01_001000.png", CV_LOAD_IMAGE_GRAYSCALE);
img2 = cvLoadImage("20090701001_avi01_001002.png", CV_LOAD_IMAGE_GRAYSCALE);
# CV_32FC1 を要素とする行列
vx = cvCreateMat(img1.height, img1.width, CV_32FC1);
# CV_32FC1 を要素とする行列
vy = cvCreateMat(img1.height, img1.width, CV_32FC1);
cvSetZero(vx); 
cvSetZero(vy); 
criteria = cvTermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 64, 0.01 );
cvCalcOpticalFlowHS( img1, img2, 0, vx, vy, 100.0, criteria );
# cvCalcOpticalFlowLK( img1, img2, cvSize(1,1), vx, vy ); 

map = gray(256);
colormap(map);

# image copy
img1mat = cvreal2d_to_mat(img1); 
imshow(img1mat, [min(min(img1mat)) max(max(img1mat))]);
input("Please press enter to continue");

img2mat = cvreal2d_to_mat(img2); 
imshow(img2mat, [min(min(img2mat)) max(max(img2mat))]);
input("Please press enter to continue");

# vx, vy copy
vxmat = cvreal2d_to_mat(vx); 
vymat = cvreal2d_to_mat(vy); 

p = max(-16, min(16, abs(vxmat) + abs(vymat)));
map = gray(256);
colormap(map);
imshow(p, [min(min(p)) max(max(p))]);
input("Please press enter to continue");

mask = ( abs(vxmat) + abs(vymat) ) > 1;
a = atan2(vymat, vxmat) .* mask; 
map = rainbow(256);
colormap(map);
imshow(a, [min(min(a)) max(max(a))]);
input("Please press enter to continue");
