我需要拍摄视频文件,将其分成几帧,确定感兴趣的区域,并将其应用于每个帧。然后,我需要确定视频中黑色像素随时间逐渐消失的百分比。视频显示颗粒移向正极,并且可以将其视为黑色/棕色液体。
到目前为止,我设法将视频分成多个帧,然后放入称为arr的数组中。我可以裁剪感兴趣的区域,但它要求我为每个区域做一个。但是,我只想执行一次并将其应用于每个框架。然后,我需要计算和绘制粒子的扩散。
我正在使用OpenCV 3.4和python 3.6。
我是python和opencv的新手,因此感谢您的帮助或建议。
def vid_frame(vid_file):
# Playing video from file inputted
video = cv2.VideoCapture(vid_file)
try:
if not os.path.exists("data"):
os.makedirs("data")
except OSError:
print("Error: creating directory of data")
currentFrame = 0
num_frames = 10
arr = []
for i in range(0, num_frames):
ret, frame = video.read()
if ret == True:
# Converts frames to gray scale
#gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
# Wait for 'q' to exit the while loop
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Saves image of the current frame in .jpg file
name = './data/file' + str(currentFrame) + '.jpg'
print('Creating...' + name)
cv2.imwrite(name, frame)
# Prevents duplicate images
currentFrame += 1
# Add frame to array
arr.append(name)
# When everything is done, release the capture
video.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
# Iterate over each frame
for i in arr:
# Read image
#im = cv2.imread(i, 0)
# 0 is the constant for cv::IMREAD_GRAYSCALE
im = cv2.imread(i, 0)
# Reduce resolution
#im = cv2.resize(im, (1000, 1000))
imC = cv2.resize(im, (int(im.shape[1] / 4), int(im.shape[0] / 4)))
# Select ROI (Region of Interest)
showCrosshair = False
fromCenter = False
r = cv2.selectROI("Image", imC, fromCenter, showCrosshair)
# Crop image
imCrop = imC[int(r[1]):int(r[1] + r[3]), int(r[0]):int(r[0] + r[2])]
# Display cropped image
cv2.imshow("Image", imCrop)
cv2.waitKey(0)
# Save the cropped image
cv2.imwrite("resize.jpg", imC)
# Get image properties
h, w = np.shape(im)
print("width:", str(w))
print("height:", str(h))
# Iterate over each pixel in the image
for py in range(0, h):
avgGray = 0.0
for px in range(0, w):
avgGray += im[py][px]
#print(im[py][px])
print("Average Gray for row ", py, " is: ", avgGray/w)
# Create the threshold
retval, threshold1 = cv2.threshold(imCrop, 12, 255,
cv2.THRESH_BINARY)
cv2.imshow("threshold1", threshold1)
# Find frequency of pixels in range 0-255
#histr = cv2.calcHist([threshold1], [0], None, [256], [0, 256])
# Show the plotting graph of an image (histogram)
plt.plot([0, 50, 100, 150, 200], [0, 1, 2, 3, 4])
# Labels and Display
plt.title("Electrophoresis Video")
plt.xlabel("Time (s)")
plt.ylabel("Interface Position (mm)")
plt.grid(True)
plt.show()