|
| 1 | +from skimage.measure import compare_ssim |
| 2 | +import argparse |
| 3 | +import imutils |
| 4 | +import cv2 |
| 5 | +import matplotlib.pyplot as plt |
| 6 | +import numpy as np |
| 7 | +plt.rcParams['image.cmap'] = 'gray' |
| 8 | + |
| 9 | +# Cargar la imagen a analizar |
| 10 | +imagen = cv2.imread("./Recursos/juego1/photo0.jpg") |
| 11 | +imagenc = imagen.copy() |
| 12 | + |
| 13 | +# Imagen de referencia o patron a comparar |
| 14 | +referencia = cv2.imread("./Recursos/juego1/ref0.jpg") |
| 15 | +refc = referencia.copy() |
| 16 | + |
| 17 | +# Convertir las imagenes a escala de grises |
| 18 | +imagenGris = cv2.cvtColor(imagen, cv2.COLOR_BGR2GRAY) |
| 19 | +referenciaGris = cv2.cvtColor(referencia, cv2.COLOR_BGR2GRAY) |
| 20 | + |
| 21 | +# Calcular el indice de similitud estructural (SSIM) entre las dos imagenes |
| 22 | +# Devuelve la imagen con las diferencias encontradas |
| 23 | +(score, diff) = compare_ssim(imagenGris, referenciaGris, full=True) |
| 24 | +diff = (diff * 255).astype("uint8") |
| 25 | + |
| 26 | +# Devuelve la similitud estructural determinada |
| 27 | +print("SSIM: {}".format(score)) |
| 28 | + |
| 29 | +# Resaltar los contornos y regiones donde difieren ambas imagenes |
| 30 | +thresh = cv2.threshold(diff, 0, 255, |
| 31 | + cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] |
| 32 | +cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, |
| 33 | + cv2.CHAIN_APPROX_SIMPLE) |
| 34 | +cnts = imutils.grab_contours(cnts) |
| 35 | + |
| 36 | +# Aplicamos un loop para cada contorno detectado |
| 37 | +for c in cnts: |
| 38 | + # Calcular el cuadro delimitador |
| 39 | + (x, y, w, h) = cv2.boundingRect(c) |
| 40 | + cv2.rectangle(imagen, (x, y), (x + w, y + h), (0, 0, 255), 2) |
| 41 | + cv2.rectangle(referencia, (x, y), (x + w, y + h), (0, 0, 255), 2) |
| 42 | + |
| 43 | +# Mostrar resultados |
| 44 | +f, axes = plt.subplots(1, 3, figsize=(16, 5)) |
| 45 | +axes[0].imshow(refc) |
| 46 | +axes[0].set_title('Referencia') |
| 47 | +axes[1].imshow(imagenc) |
| 48 | +axes[1].set_title('Imagen') |
| 49 | +axes[2].imshow(diff) |
| 50 | +axes[2].set_title('Diferencias') |
| 51 | + |
| 52 | +for ax in axes: |
| 53 | + ax.axis('off') |
| 54 | +plt.show() |
| 55 | + |
| 56 | +#Guardar imagen |
| 57 | +cv2.imwrite("./Recursos/juego1/ejemplo.png",diff) |
| 58 | + |
| 59 | +#Bibliografia: https://www.pyimagesearch.com/2017/06/19/image-difference-with-opencv-and-python/ |
0 commit comments