[英]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我有这个代码我想打印两个图像中差异中心的
(x,y)
坐标
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.
然后,您可以找到差异的轮廓,并使用 boundingRect 计算中心。
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:如果您的意思是打印 2 个不同图像的中心:
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我使用了代表 Pillow 的 PIL 你可以使用 pip install Pillow 下载它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.