파이썬 이미지 비교
DB CAFE
thumb_up 추천메뉴 바로가기
- DBA { Oracle DBA 명령어 > DBA 초급 과정 > DBA 고급 과정 }
- 튜닝 { 오라클 튜닝 목록 }
- 모델링 { 데이터 모델링 가이드 }
- 이미지 비교
1 이미지 비교 1번째 [편집]
import cv2
# Load the two images
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
# Calculate the absolute difference between the two images
diff = cv2.absdiff(img1, img2)
# Display the difference image
cv2.imshow('Difference Image', diff)
cv2.waitKey(0)
cv2.destroyAllWindows()
2 이미지 비교 2번째[편집]
import cv2
# Load the two images
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
# Convert the images to grayscale
gray_img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray_img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# Calculate the structural similarity index (SSIM) between the two images
ssim = cv2.compare_ssim(gray_img1, gray_img2)
# Display the SSIM value
print("The SSIM value between the two images is: {}".format(ssim))
3 이미지 비교 3번째 [편집]
from PIL import Image, ImageChops
# Load the images
image1 = Image.open("image1.jpg")
image2 = Image.open("image2.jpg")
# Compare the images
diff = ImageChops.difference(image1, image2)
# Check if the images are the same
if diff.getbbox() is None:
print("The images are the same")
else:
print("The images are different")
4 이미지비교 3[편집]
from PIL import Image
import numpy as np
from skimage.metrics import structural_similarity as ssim
def mse(imageA, imageB):
err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
err /= float(imageA.shape[0] * imageA.shape[1])
return err
def compare_images(image_path1, image_path2):
image1 = Image.open(image_path1).convert("L") # Convert to grayscale
image2 = Image.open(image_path2).convert("L")
image1_np = np.array(image1)
image2_np = np.array(image2)
mse_value = mse(image1_np, image2_np)
ssim_value = ssim(image1_np, image2_np)
return mse_value, ssim_value
if __name__ == "__main__":
image_path1 = "path/to/your/image1.jpg"
image_path2 = "path/to/your/image2.jpg"
mse_value, ssim_value = compare_images(image_path1, image_path2)
print(f"MSE: {mse_value}")
print(f"SSIM: {ssim_value}")
Replace the image_path1 and image_path2 with the paths to your images. The MSE is a measure of the difference between the two images, with a smaller value indicating a higher similarity. The SSIM is a measure of structural similarity, with a value between -1 and 1, where a higher value indicates higher similarity.
The code above will convert the images to grayscale before comparing them. If you want to compare images in color, remove the .convert("L") and update the ssim function call to ssim(image1_np, image2_np, multichannel=True).
Remember that this approach works best for images of the same size. If you need to compare images with different sizes, you should resize them before performing the comparison.