PIL Image to CV2 image

Bands need to be reversed for CV2. PIL is RGB. CV2 is BGR.
Also, if you are getting errors with CV2, it may be because it doesn’t like transformed ‘views’ of arrays. Use the copy method.

# PIL RGB 'im' to CV2 BGR 'imcv'
imcv = np.asarray(im)[:,:,::-1].copy()
# Or
imcv = cv2.cvtColor(np.asarray(im), cv2.COLOR_RGB2BGR)
# To gray image
imcv = np.asarray(im.convert('L'))
# Or
imcv = cv2.cvtColor(np.asarray(im), cv2.COLOR_RGB2GRAY)
view raw gistfile1.py hosted with ❤ by GitHub

PIL and CV2 use the same percentages of R,G, and B to make a greyscale image but the results may have a difference of 1 in many places due to rounding off. PIL uses integer division and CV2 uses floating point percentages.
PIL: GRAY = R * 299/1000 + G * 587/1000 + B * 114/1000
CV2: GRAY = R * 0.299 + G * 0.587 + B * 0.114

If the PIL image has four bands, only reverse the first three.

Epipole and Epipolar Lines

Epipole from essential matrix:
e1c2 is the position of camera 2 in image 1 coordinates. (Plot it in image 1)

def epipoleSVD(M):
    V = cv2.SVDecomp(M)[2]
    return V[-1]/V[-1,-1]
e1c2 = epipoleSVD(E)
e2c1 = epipoleSVD(E.T)

Note: This cv2 method returns three values, [S, U, V], but only V is needed to find the epipole. The epipole is in form [x,y,1].

Epipolar lines from essential matrix:
elines1 (a 3xN array) are drawn on image 1 and will converge at e1c2 (from above). x1 and x2 are normalized 3xN arrays of corresponding points in image 1 and image 2. (A line vector contains the values [a,b,c] in ax+by+c=0)

elines2 = dot(E, x1)
elines1 = dot(E.T, x2) #or dot(x2.T, E).T

To plot these lines, try the following:

def lines2points(lines, epipole):
    xmax = ones(lines.shape[1])*epipole[0]
    a,c = lines[0]/lines[1], lines[2]/lines[1]
    x = array([-xmax,xmax])
    y = array([r_[-a*Lx[0] - c], r_[-a*Lx[1] - c]])
    return x, y
Lx,Ly = lines2points( dot(E, x1), epipoleSVD(E.T) )
plt.plot(Lx, Ly, 'r')

Note: This will overlay epipolar lines derived from image 1 on corresponding points in image 2 that are between +/- epipole x-coordinate.