(image1_path, image2_path)
| 1 | import cv2 |
| 2 | def compare_images(image1_path, image2_path): |
| 3 | # Read the images |
| 4 | image1 = cv2.imread(image1_path) |
| 5 | image2 = cv2.imread(image2_path) |
| 6 | # Check if the images were loaded successfully |
| 7 | if image1 is None or image2 is None: |
| 8 | print("Failed to load the images.") |
| 9 | return |
| 10 | # Resize the images to the same dimensions for comparison |
| 11 | image1 = cv2.resize(image1, (500, 500)) |
| 12 | image2 = cv2.resize(image2, (500, 500)) |
| 13 | |
| 14 | #calculating difference between two images |
| 15 | difference = cv2.subtract(image1, image2) |
| 16 | b, g, r = cv2.split(difference) |
| 17 | # If the images are identical, the difference should be black (all zeros) |
| 18 | if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0: |
| 19 | print("The images are identical.") |
| 20 | else: |
| 21 | # color the mask red |
| 22 | conv_hsv_gray = cv2.cvtColor(difference, cv2.COLOR_BGR2GRAY) |
| 23 | ret, mask = cv2.threshold( |
| 24 | conv_hsv_gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU |
| 25 | ) |
| 26 | difference[mask != 255] = [0, 0, 255] |
| 27 | |
| 28 | # add the red mask to the images to make the differences obvious |
| 29 | image1[mask != 255] = [0, 0, 255] |
| 30 | image2[mask != 255] = [0, 0, 255] |
| 31 | diff ="diff.png" |
| 32 | cv2.imwrite(diff, difference) |
| 33 | print("The images are different.") |
| 34 | |
| 35 | |
| 36 | # Provide the paths to the two images you want to compare |
no test coverage detected