Skip to content

Instantly share code, notes, and snippets.

@crackwitz
Created August 17, 2021 16:19
Show Gist options
  • Save crackwitz/b8867b46f320eae17f4b2684416c79ea to your computer and use it in GitHub Desktop.
Save crackwitz/b8867b46f320eae17f4b2684416c79ea to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import os
import sys
import numpy as np
import cv2 as cv
np.set_printoptions(suppress=True)
im = cv.imread("BrOry.jpg", cv.IMREAD_UNCHANGED)
(height, width) = im.shape[:2]
roi = (rx, ry, rw, rh) = (166, 158, 219, 112)
(B,G,R) = np.transpose(im, axes=(2,0,1))
cv.imshow("B", B[ry:ry+rh, rx:rx+rw])
cv.imshow("G", G[ry:ry+rh, rx:rx+rw])
cv.imshow("R", R[ry:ry+rh, rx:rx+rw])
cv.waitKey(1)
M_blue = np.eye(3, dtype=np.float32)
M_red = np.eye(3, dtype=np.float32)
if os.path.exists("M_blue.npy"):
M_blue = np.load("M_blue.npy")
if os.path.exists("M_red.npy"):
M_red = np.load("M_red.npy")
#termcrit = (cv.TERM_CRITERIA_COUNT | cv.TERM_CRITERIA_EPS, 50, 0.001)
termcrit = (cv.TERM_CRITERIA_COUNT | cv.TERM_CRITERIA_EPS, 20, 0.5e-3)
gaussFiltSize = 5 # default 5
motionType = cv.MOTION_HOMOGRAPHY
#motionType = cv.MOTION_AFFINE
#motionType = cv.MOTION_EUCLIDEAN
if motionType == cv.MOTION_HOMOGRAPHY:
Mrows = 3
else:
Mrows = 2
M_red[2] = (0,0,1)
M_blue[2] = (0,0,1)
print("ECC blue...", end=" ", flush=True)
(rv, res) = cv.findTransformECC(
templateImage=G,
inputImage=B,
warpMatrix=M_blue[:Mrows],
motionType=motionType,
criteria=termcrit,
inputMask=None,
gaussFiltSize=gaussFiltSize
)
print(f"done. ECC = {rv:.4f}")
M_blue[:Mrows] = res
np.save("M_blue.npy", M_blue)
print(M_blue)
print("ECC red...", end=" ", flush=True)
(rv, res) = cv.findTransformECC(
templateImage=G,
inputImage=R,
warpMatrix=M_red[:Mrows],
motionType=motionType,
criteria=termcrit,
inputMask=None,
gaussFiltSize=gaussFiltSize
)
print(f"done. ECC = {rv:.4f}")
M_red[:Mrows] = res
np.save("M_red.npy", M_red)
print(M_red)
#B_warped = cv.warpAffine(R, M[0:2,0:3], (width, height), flags=cv.WARP_INVERSE_MAP | cv.INTER_LINEAR)
B_warped = cv.warpPerspective(B, M_blue, (width, height), flags=cv.WARP_INVERSE_MAP | cv.INTER_CUBIC)
R_warped = cv.warpPerspective(R, M_red, (width, height), flags=cv.WARP_INVERSE_MAP | cv.INTER_CUBIC)
cv.imshow("B_warped", B_warped[ry:ry+rh, rx:rx+rw])
cv.imshow("R_warped", R_warped[ry:ry+rh, rx:rx+rw])
composite = np.dstack([B_warped, G, R_warped])
cv.imwrite("composite.png", composite)
print("composite written")
cv.waitKey(-1)
cv.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment