如何使用Opencv进行图像比较?

问题描述 投票:0回答:1

预计会突出显示两个图像之间的变化或差异区域:

1. ![图片1][1]

2. ![图片2][2]

编写的代码是:

from pdf2image import convert_from_path # Used to convert pdf to image
import cv2
import numpy as np
from PIL import Image, ImageOps
from IPython.display import display

def process_and_display_image(pdf_path, target_size=(800, 600),save_path='processed_image.jpeg'):
    
    # Convert PDF to image
    images = convert_from_path(pdf_path)

    # Since there is only 1 image in the pdf
    image = images[0]

    # Automatically rotates the image if needed
    image = ImageOps.exif_transpose(image)

    # Resize image to target size
    image.thumbnail(target_size, Image.Resampling.LANCZOS)

    # Convert to numpy array for any advanced processing
    image_np = np.array(image)

    # Converting to grayscale to reduce variations
    image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)

    # Convert back to PIL image to display in Jupyter
    image_processed = Image.fromarray(image_np)

    # Display the processed image
    display(image_processed)

    # Save the processed image to a file
    image_processed.save(save_path, 'JPEG')
    print(f"Image saved as {save_path}")


import matplotlib.pyplot as plt
# Read the image
image1 = cv2.imread('file_1.jpeg', cv2.IMREAD_UNCHANGED)

# Convert the image from BGR to RGB 
image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)

image2 = cv2.imread('file_2.jpeg', cv2.IMREAD_UNCHANGED)
image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2RGB)

if image1.shape == image2.shape:
    difference = cv2.absdiff(image1,image2)
    difference = cv2.cvtColor(difference, cv2.COLOR_BGR2RGB)
    b,g,r=cv2.split(difference)

plt.imshow(difference)
plt.axis('off')
plt.show()
  • 实际结果:

actual_output

  • 预计会有以下结果:

desired_output

以下是供您细读/理解的图像 [1]:https://i.stack.imgur.com/ngSQt.jpg [2]:https://i.stack.imgur.com/1tKgn.jpg

python opencv image-processing
1个回答
0
投票

改变:

if image1.shape == image2.shape:
    difference = cv2.absdiff(image1,image2)
    difference = cv2.cvtColor(difference, cv2.COLOR_BGR2RGB)
    b,g,r=cv2.split(difference)


plt.imshow(difference)
plt.axis('off')
plt.show()

至:

if image1.shape == image2.shape:
    difference = cv2.absdiff(image1,image2)


difference = 255 - difference

plt.imshow(difference)
plt.axis('off')
plt.show()

获得:

或者按照评论中的建议,仅使用:

if image1.shape == image2.shape:
    
    overlay = cv2.addWeighted(image1, 0.5, image2, 0.5, 0) 
       
difference = overlay

plt.imshow(difference)
plt.axis('off')
plt.show()

获得:

© www.soinside.com 2019 - 2024. All rights reserved.