简体   繁体   中英

how I can print (x,y) coordinate for the center of difference between images in this code?

I have this code I want to print the (x,y) coordinate for the center of difference in the 2 images

import cv2
import numpy as np


original = cv2.imread("images/original_1.png")
duplicate = cv2.imread("images/original_1_edit.png")


#start image process
# check if 2 images are equals
if original.shape == duplicate.shape:
    print("The images have same size and channels")
    differenc = cv2.subtract(original, duplicate)
    #check the channelas RGB
    b, g, r = cv2.split(differenc)
    cv2.imshow("differenc", differenc)
    if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
        print("The images completely Equal")

cv2.imshow("Original", original)
cv2.imshow("Duplicate", original)
cv2.waitKey(0)
cv2.destroyAllWindows()

When you subtract the images, the result shows the difference. You can turn that into a mask using thresholding. You can then find the contours of the differences, and calculate the center using the boundingRect.

Result:
在此处输入图片说明

Code:

    import cv2
    import numpy as np

     # load images
    img = cv2.imread("image.png")
    img2 = cv2.imread("image2.png")
    # create copy for image comparison
    img2_ori = img2.copy()
    # subtract to get difference
    diff =  cv2.subtract(img, img2)
    # create grayscale of diff
    gray =  cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
    # create a mask for the non black values (above 10) 
    ret,thresh1 = cv2.threshold(gray,10,255,cv2.THRESH_BINARY)
    # find contours in mask
    contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # calculate the center of each contour using the boundingrect
    for cnt in contours:
            x,y,w,h = cv2.boundingRect(cnt)
            centerX = x+ int(w/2)
            centerY = y+ int(h/2)
            print(centerX)
            print(centerY)
            # draw blue dot in center
            cv2.circle(img2,(centerX, centerY),5,(255,0,0),-1)
    #show images
    cv2.imshow("img", img)
    cv2.imshow("img2", img2_ori)
    cv2.imshow("diff", thresh1)
    cv2.imshow("result", img2)

    cv2.waitKey(0)
    cv2.destroyAllWindows() 

If you meant print the center of 2 different images:

from PIL import Image

img1 = Image.open("occhio1.jpg")
img2 = Image.open("occhio2.jpg")

center1 = (img1.width / 2, img1.height / 2)
center2 = (img2.width / 2, img2.height / 2)

print(str(center1) + " " + str(center2))

I used PIL that stands for Pillow you can download it using pip install pillow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM