Anda di halaman 1dari 3

from math import *

import numpy as np
import cv2
from matplotlib import pyplot as plt

def trans_param(x1,y1,x1d,y1d,x2,y2,x2d,y2d):
# c = cos(th); s = sin(th)
# x1*c - y1*s + tx = x1d -> (1)
# x1*s + y1*c + ty = y1d -> (2)
# x2*c - y2*s + tx = x2d -> (3)
# x2*s + y2*c + ty = y1d -> (4)
# (3) - (1) -> x1n*c - y1n*s = d1n; # x1n = x2-x1
# (4) - (2) -> y1n*c + x1n*s = d2n; # y1n = y2-y1
x1n = x2-x1
y1n = y2-y1
d1n = x2d - x1d
d2n = y2d - y1d
a = np.array([[x1n,-y1n], [y1n,x1n]])
b = np.array([d1n,d2n])
x = np.linalg.solve(a,b)
phi = np.arcsin(x[1])
c = cos(phi)
s = sin(phi)
tx = x1d - x1*c + y1*s
ty = y1d - x1*s - y1*c
return phi, tx, ty

# Source Images = I1 and I2


I1 = cv2.imread('Image1 Path',0)
I2 = cv2.imread('Image2 Path',0)
(h1,l1) = I1.shape
(h2,l2) = I2.shape

# trans_param(x1,y1,x1d,y1d,x2,y2,x2d,y2d)
(phi,tx,ty) = trans_param(125,30,249,94,373,158,400,329)
# (phi,tx,ty) = trans_param(496,53,559,299,19,269,37,248)

# Convention in this code: positive angle -> clockwise rotation


# Angle 'phi' is in radians
# Conversion of tilt angle to degrees
th = phi*(180/math.pi)

# Rotation matrix
R = np.array([(cos(phi),-sin(phi)),(sin(phi),cos(phi))])
# Inverse of rotation matrix
Rinv = np.linalg.inv(R)

# Translation vector
T = np.array([[tx],[ty]])

# Fixing the target canvas size


ht = h2 # Target height
lt = l2 # Target length
# Target image = A
A = np.zeros((ht,lt))

for yt in range(ht):
for xt in range(lt):
P = np.array([[xt],[yt]])
Ps = P - T
Ps = np.matmul(Rinv,Ps)
xs = Ps[0][0]
ys = Ps[1][0]
x = int(np.floor(xs))
y = int(np.floor(ys))
a = xs - x
b = ys - y

# For bilinear interpolation in Target to Source mapping:


# A[yt][xt] = (1-a)*(1-b)*I[y][x] + (1-a)*(b)*I[y+1][x] + (a)*(1-
b)*I[y][x+1] + (a)*(b)*I[y+1][x+1]
if y>=0 and y<h1 and x>=0 and x<l1:
A[yt][xt] = (1-a)*(1-b)*I1[y][x]
if y>=0 and y+1<h1 and x>=0 and x<l1:
A[yt][xt] = A[yt][xt] + (1-a)*(b)*I1[y+1][x]
if y>=0 and y<h1 and x>=0 and x+1<l1:
A[yt][xt] = A[yt][xt] + (a)*(1-b)*I1[y][x+1]
if y>=0 and y+1<h1 and x>=0 and x+1<l1:
A[yt][xt] = A[yt][xt] + (a)*(b)*I1[y+1][x+1]

D = abs(A - I2)
D1 = np.zeros((ht,xt))

for ye in range(ht):
for xe in range(xt):
if D[ye][xe] >= 100:
D1[ye][xe] = 255
else:
D1[ye][xe] = 0

plt.figure(1)
plt.subplot(1,2,1)
plt.imshow(I1, cmap = 'gray')
plt.title('Source Image 1')
plt.subplot(1,2,2)
plt.imshow(A, cmap = 'gray')
plt.title('Transformed Image')
plt.figure(2)
plt.subplot(1,3,1)
plt.imshow(I2, cmap = 'gray')
plt.title('Source Image 2')
plt.subplot(1,3,2)
plt.imshow(A, cmap = 'gray')
plt.title('Source Image 1 -> Transformed')
plt.subplot(1,3,3)
plt.imshow(D, cmap = 'gray')
plt.title('Difference Image')
plt.figure(3)
plt.subplot(1,3,1)
plt.imshow(I2, cmap = 'gray')
plt.title('Source Image 2')
plt.subplot(1,3,2)
plt.imshow(A, cmap = 'gray')
plt.title('Source Image 1 -> Transformed')
plt.subplot(1,3,3)
plt.imshow(D1, cmap = 'gray')
plt.title('Difference Image - High Contrast')
plt.show()

Anda mungkin juga menyukai