# find moving image.
#
# running the program pops up a window to watch the video.
# the program video window shows the first monitor,
# but watch the program video window on second extended monitor
import cv2
import numpy as np
# Path to video file
cap = cv2.VideoCapture(
1,
apiPreference=cv2.CAP_ANY,
params=[cv2.CAP_PROP_FRAME_WIDTH, 1280, cv2.CAP_PROP_FRAME_HEIGHT, 720],
) # I made cap = 1280, 720 resolution to speed the program up on my computer. I have a rtx 3060, obs studio at 60 fps
# Used as counter variable
count = 1
# checks whether frames were extracted
success = 1
# create frame_1 and frame_2 to be able to use the frames between if conditions
frame_1 = 0
frame_2 = 0
# get 2 frames to start with
count_subtraction = 0
while success:
# function extract frames
success, image = cap.read()
if count_subtraction == 0:
if count <= 2:
# Saves the frames with frame-count
cv2.imwrite("frame_%d.jpg" % count, image, [int(cv2.IMWRITE_JPEG_QUALITY), 100]) # jpg 100% quality
count += 1
if count == 3:
frame_1 = cv2.imread("frame_1.jpg", 0)
frame_2 = cv2.imread("frame_2.jpg", 0)
# use the frames below
# Create the sharpening kernel
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
# Sharpen the image
frame_1 = cv2.filter2D(frame_1, -1, kernel)
frame_2 = cv2.filter2D(frame_2, -1, kernel)
# subtract the images
subtracted = cv2.subtract(frame_2, frame_1)
subtracted_sharpened = cv2.filter2D(subtracted, -1, kernel)
# TO show the output
cv2.imshow("image", subtracted_sharpened)
# the else condition to count_subtraction needs a first frame
frame_1 = frame_2
count = 1
count_subtraction = 1
else:
cv2.imwrite("frame_2.jpg", image, [int(cv2.IMWRITE_JPEG_QUALITY), 100]) # jpg 100% quality
frame_2 = cv2.imread("frame_2.jpg", 0)
# use the frames below
# Create the sharpening kernel
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
# Sharpen the image
frame_2 = cv2.filter2D(frame_2, -1, kernel)
# subtract the images
subtracted = cv2.subtract(frame_2, frame_1)
subtracted_sharpened = cv2.filter2D(subtracted, -1, kernel)
# TO show the output
cv2.imshow("image", subtracted_sharpened)
# the second frame becomes a first frame
frame_1 = frame_2
if cv2.waitKey(1) & 0xFF == ord("q"):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
5条答案
按热度按时间e4yzc0pl1#
试试background subtraction。
使用
cv2.subtract(img1,img2)
代替算术运算,因为cv2会处理负值。brgchamk2#
如果两张图片中的背景完全相同,您可以将它们减去,就像您在帖子中提到的那样。
字符串
0pizxfdo3#
@dvigneshwr的答案做减法,其中得到的负值向上舍入为0。@Taha Anwar M-Holmes的答案保留了否定的结果,但改变了结果数组的数据类型,因此它不再是传统的图像类型。
对于那些希望根据 * 绝对值差 * 从背景图像中识别前景并返回与输入相同数据类型的数组的人(这就是我在这里结束的原因),使用absdiff。
假设数组的宽度和高度都一样……
字符串
值得注意的是,OP没有提供任何细节wrt的图像被减去在这里...根据图像的内容,所有这些方法都可以回答OP的问题。
7ivaypg94#
cv2.subtract不工作,它只是绑定0-255之间的值,所以如果你想得到负值,只需将图像从unit 8转换为int 32或int 64。注意unint 8只能接受0-255的值,因此它不能处理负值。
字符串
xn1cxnb45#
字符串