将numpy的基础类型转化为int型否则uint8会发生溢出
在cv2里面两幅图一定要先转换成int型, 相减,然后在转换为uint8
def diffimage(src_1, src_2): # 将numpy的基础类型转化为int型否则uint8会发生溢出 src_1 = src_1.astype(np.int) src_2 = src_2.astype(np.int) diff = abs(src_1 - src_2) return diff.astype(np.uint8)
背景如图
如果直接相减
import cv2
import numpy as np
background = cv2.imread('t_background.jpg')
img = cv2.imread('img.jpg')
diff = background - img
cv2.imshow('', diff)
会得到
加上下面就可以了
def diffimage(src_1, src_2):
# 将numpy的基础类型转化为int型否则uint8会发生溢出
src_1 = src_1.astype(np.int)
src_2 = src_2.astype(np.int)
diff = abs(src_1 - src_2)
return diff.astype(np.uint8)
完整代码
import cv2
import numpy as np
def diffimage(src_1, src_2):
# 将numpy的基础类型转化为int型否则uint8会发生溢出
src_1 = src_1.astype(np.int)
src_2 = src_2.astype(np.int)
diff = abs(src_1 - src_2)
return diff.astype(np.uint8)
background = cv2.imread('t_background.jpg')
img = cv2.imread('img.jpg')
# diff = background - img
diff = diffimage(background, img)
cv2.imshow('', diff)