Está en la página 1de 8

Universidad Nacional de San Agustín

Facultad de Ingeniería de Producción y Servicios


Escuela Profesional Ciencia de la Computación

Computación Gráfica

Practica 9-2 Operadores Geométricos

GRUPO N◦ 8
ALUMNOS:

GOMEZ CONTRERAS, JUNIOR


PILCO PANCCA, LUZ MARINA
SEJJE CONDORI, ERIKA
TORRES LIMA, JOSE

DOCENTE:
MACHACA ARCEDA, VICENTE

AREQUIPA - PERÚ

2020
Practica N◦9.2
1. Ejercicios
1. Solucione el problema de la rotación de imágenes al utilizar warpAffine.

a) Código
1 import sys
2 import cv2
3 import numpy as np
4 import math
5 def My_warpAffine(img, M, widthI, heightI):
6 h, w, c = img.shape
7 img_out = np.zeros((heightI, widthI, c), np.uint8)
8 A = np.array([[M[1][1],M[1][0]],[M[0][1],M[0][0]]])
9 B = np.array([[M[1][2]],[M[0][2]]])
10 for i in range(h):
11 for j in range(w):
12 X = np.array([[i],[j]])
13 M1 = np.dot(A, X) + B
14 M1 = M1.astype(int)
15 if (M1[0,0] > 0 and M1[0,0] < heightI and M1[1,0] > 0 and M1[1,0] <
widthI):
16 for k in range(c):
17 img_out[M1[0, 0], M1[1, 0]] = img[i][j]
18 return img_out
19 def My_warpAffine_M(img, M, widthI, heightI):
20 h, w, c = img.shape
21 img_out = np.zeros((heightI, widthI, c), np.uint8)
22 X = np.array([[0],[0]], dtype=np.float32)
23 A = M[:2, :2]
24 B = M[:, 2:]
25 for i in range(widthI):
26 for j in range(heightI):
27 Y1 = np.array([[i],[j]], dtype=np.float32)
28 Y = Y1 - B
29 #M1 = np.linalg.inv(A).dot(Y)
30 M2 = cv2.solve(A,Y,X)
31 M1 = M2[1].astype(int)
32 if (M1[1,0] > 0 and M1[1,0] < h and M1[0,0] > 0 and M1[0,0] < w):
33 for k in range(c):
34 img_out[j, i] = img[M1[1, 0]][M1[0, 0]]
35 return img_out
36 def Translate(img, x, y):
37 h, w = img.shape[:2]
38 A = np.identity(2)
39 B = [[x],[y]]
40 M = np.concatenate((A, B), axis=1)
41 img_out = My_warpAffine_M(img, M, w, h)
42 return img_out
43 def Scale(img, x, y):
44 h, w = img.shape[:2]
45 A = np.float32([[x,0],[0,y]])
46 B = [[0],[0]]

1
47 M = np.concatenate((A, B), axis=1)
48 img_out = My_warpAffine_M(img, M, w, h)
49 return img_out
50 def Rotation(img, angle):
51 h, w = img.shape[:2]
52 img_c = (w / 2, h / 2)
53 rad = math.radians(angle)
54 sin = math.sin(rad)
55 cos = math.cos(rad)
56 b_w = int((h * abs(sin)) + (w * abs(cos)))
57 b_h = int((h * abs(cos)) + (w * abs(sin)))
58 mid_h = int((h+1)/2)
59 mid_w = int((w+1)/2)
60 A = np.float32([[cos,sin],[-sin,cos]])
61 B = np.float32([[((1-cos)*mid_w)-(sin*mid_h)],[(sin*mid_w)+(1-cos)*mid_h]])
62 M = np.concatenate((A, B), axis=1)
63 M[0, 2] += ((b_w / 2) - img_c[0])
64 M[1, 2] += ((b_h / 2) - img_c[1])
65 img_out = My_warpAffine_M(img, M, b_w, b_h)
66 return img_out
67 def Shear(img, x, y):
68 h, w = img.shape[:2]
69 ix = math.tan(x * math.pi / 180)
70 iy = math.tan(y * math.pi / 180)
71 A = np.float32([[1,ix,0],[iy,1,0]])
72 B = [[0],[0]]
73 M = np.concatenate((A, B), axis=1)
74 img_out = My_warpAffine_M(img, M, w+256, h+256)
75 return img_out
76 if __name__ == "__main__":
77 filename = sys.argv[1]
78 img = cv2.imread(filename)
79 heigth = img.shape[0]
80 width = img.shape[1]
81 img_out = np.zeros((heigth, width, 3),np.uint8)
82 img_outT = Translate(img, 70, 70)
83 cv2.imwrite(’resultado_1T.png’, img_outT)
84 cv2.imshow(’resultado_1T.png’, img_outT)
85 cv2.waitKey(0)
86 img_outSc = Scale(img, 0.7, 0.8)
87 cv2.imwrite(’resultado_1Sc.png’, img_outSc)
88 cv2.imshow(’resultado_1Sc.png’, img_outSc)
89 cv2.waitKey(0)
90 img_outR = Rotation(img, 45)
91 cv2.imwrite(’resultado_1R.png’, img_outR)
92 cv2.imshow(’resultado_1R.png’, img_outR)
93 cv2.waitKey(0)
94 img_outSh = Shear(img, 20, 15)
95 cv2.imwrite(’resultado_1Sh.png’, img_outSh)
96 cv2.imshow(’resultado_1Sh.png’, img_outSh)
97 cv2.waitKey(0)
98 cv2.destroyAllWindows()
99 cv2.waitKey(1)
100 exit()

2
Explicación: Se ha probado nuestro “My_warpAffine” y durante la rotación de la imagen se han
perdido píxeles, al probar nuestro “My_warpAffine_M” este problema se ha mejorado enorme-
mente, dado que este nuevo algoritmo calcula los puntos de entrada en base a los puntos de salida.

b) Resultados

Figura 1.1: Imagen original Figura 1.2: Imagen con problema de rotación

Figura 1.3: Imagen aplicando “My_warpAffine” Figura 1.4: Imagen aplicando “My_warpAffine_M”

3
2. OpenCV utiliza la función cv2.getAffineTransform(pts1,pts2) para obtener la matriz M a partir de dos
puntos. Implemente su propia versión de la función getAffineTransform.

Función cv2.getAffineTransform(pts1,pts2)
a) Código
1 import cv2
2 import numpy as np
3 import matplotlib.pyplot as plt
4 #import matplotlib as plt
5
6 img = cv2.imread(’drawing.png’)
7 rows,cols,ch = img.shape
8
9 pts1 = np.float32([[50,50],[200,50],[50,200]])
10 pts2 = np.float32([[10,100],[200,50],[100,250]])
11
12 M = cv2.getAffineTransform(pts1,pts2)
13
14 dst = cv2.warpAffine(img,M,(cols,rows))
15
16 plt.subplot(121),plt.imshow(img),plt.title(’Input’)
17 plt.subplot(122),plt.imshow(dst),plt.title(’Output’)
18 plt.savefig(’R1.png’)
19 plt.show()

b) Resultados

Figura 1.5: Con Opencv

4
Implementación de nuestra propia función getAffineTransform.
a) Código
1 import cv2
2 import numpy as np
3 import matplotlib.pyplot as plt
4 #import matplotlib as plt
5
6 img = cv2.imread(’drawing.png’)
7 rows,cols,ch = img.shape
8
9 def My_warpAffine(img, M, widthI, heightI):
10 h, w, c = img.shape
11 img_out = np.zeros((heightI, widthI, c), np.uint8)
12 A = np.array([[M[1][1],M[1][0]],[M[0][1],M[0][0]]])
13 B = np.array([[M[1][2]],[M[0][2]]])
14 P = 0
15 for i in range(h):
16 for j in range(w):
17 X = np.array([[i],[j]])
18 M1 = (np.dot(A, X) + B)
19 M1 = M1.astype(int)
20 if (M1[0,0] > 0 and M1[0,0] < heightI and M1[1,0] > 0 and M1[1,0] <
widthI):
21 for k in range(c):
22 img_out[M1[0, 0], M1[1, 0]] = img[i][j]
23 return img_out
24
25 def My_affineTransform(pts1,pts2):
26 R = []
27 for i in range(2):
28 A = []
29 for j in range(len(pts1)):
30 A_ = [pts1[j][0],pts1[j][1],1]
31 A.append(A_)
32 B = [pts2[0][i],pts2[1][i],pts2[2][i]]
33 X = np.linalg.inv(A).dot(B)
34 #X = np.linalg.solve(A,B)
35 R.append([X[0],X[1],X[2]])
36 return R
37
38 pts1 = np.float32([[50,50],[200,50],[50,200]])
39 pts2 = np.float32([[10,100],[200,50],[100,250]])
40
41 M = My_affineTransform(pts1,pts2)
42 dst = cv2.warpAffine(img,np.float32(M),(cols,rows))
43
44 plt.subplot(121),plt.imshow(img),plt.title(’Input’)
45 plt.subplot(122),plt.imshow(dst),plt.title(’Output’)
46 plt.savefig(’R2_.png’)
47 plt.show()

5
Explicación: En nuestra implementación, Para encontrar la matriz de transformación, tiene como
datos de entrada pos puntos, el primer punto tiene tres puntos de la imagen de entrada y el segundo
punto tiene sus ubicaciones correspondientes en la imagen de salida. Creamos una matriz de 2x3
sera el dato de entrada para warpaffine.
b) Resultados

Figura 1.6: Resultado de nuestra propia versión

Comparando ambas Implementaciones:

1 pts1 = np.float32([[10,50],[200,50],[50,200]])
2 pts2 = np.float32([[10,100],[200,50],[100,250]])
3
4 M = My_affineTransform(pts1,pts2)
5 dst = cv2.warpAffine(img,np.float32(M),(cols,rows))
6
7 Mcv = cv2.getAffineTransform(pts1,pts2)
8 dstcv = cv2.warpAffine(img,Mcv,(cols,rows))
9
10 #plt.subplot(121),plt.imshow(img),plt.title(’Input’)
11 plt.subplot(121),plt.imshow(dstcv),plt.title(’cv2.getAffineTransform’)
12 plt.subplot(122),plt.imshow(dstcv),plt.title(’My_affineTransform’)
13 plt.savefig(’Resultado_2.png’)
14 plt.show()

6
Figura 1.7: Obtenemos el mismo resultado

2. Repositorio
https://github.com/Jomat18/Computacion-Grafica

3. Conclusiones
En la transformación Affine, todas las líneas paralelas en la imagen original seguirán siendo paralelas
en la imagen de salida.

También podría gustarte