windows下python,使用笔记本摄像头进行连续截图,并进行灰度、二值化处理

程序使用Geany编辑,生成图片存在程序文件同目录下名为“image2”的文件夹中,注意需要自己建文件夹,程序没新建,测试结果每两帧截取一幅图像,并存在文件夹中



如上图,输入S,开始截图,每两帧一次,一共进行20次,完成后还可以输入s,退出输入q

效果如下:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  snapshots.py
#  
#  Copyright 2017 Administrator <Administrator@XL-20151026NQDZ>
#  
import cv2
import numpy as np
import time
import os
from matplotlib import pyplot as plt  

def anaoshots():
	#print(time.strftime('%M:%S',time.localtime(time.time())))
	vc = cv2.VideoCapture(0)  #笔记本内置摄像头一般为 0
	#vc = cv2.VideoCapture('Test2.mp4') #读入视频文件
	c = 1
	if vc.isOpened(): #判断是否正常打开
		rval,frame = vc.read()
	   # print("read ok")
	else:
		rval = False
		print("read error")
	timeF = 2  #视频帧计数间隔频率
	while rval:   #循环读取视频帧
		rval, frame = vc.read()
		if(c%timeF == 0): #每隔timeF帧进行存储操作
			cv2.imwrite('image2/'+str(c) + '.jpg',frame) #存储为图像
  
			img = cv2.imread('image2/'+str(c) + '.jpg')  
			GrayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)  
			# 中值滤波  
			GrayImage= cv2.medianBlur(GrayImage,5) 
			ret,th1 = cv2.threshold(GrayImage,100,255,cv2.THRESH_BINARY)  
			#3 为Block size, 5为param1值  
			th2 = cv2.adaptiveThreshold(GrayImage,255,cv2.ADAPTIVE_THRESH_MEAN_C,
								cv2.THRESH_BINARY,3,5)  
			th3 = cv2.adaptiveThreshold(GrayImage,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,  
								cv2.THRESH_BINARY,3,5)  
			titles = ['Gray Image', 'Global Thresholding (v = 107)',  
			'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']  
			cv2.imwrite('image2/GrayImage'+str(c) + '.jpg',GrayImage) #存储为图像
			cv2.imwrite('image2/th1-'+str(c) + '.jpg',th1) #存储为图像
			cv2.imwrite('image2/th2-'+str(c) + '.jpg',th2) #存储为图像
			cv2.imwrite('image2/th3-'+str(c) + '.jpg',th3) #存储为图像
			#images = [GrayImage, th1, th2, th3]  
			#for i in range(4):  
			 #  plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')  
			#   plt.title(titles[i])  
			#   plt.xticks([]),plt.yticks([])  
			#plt.show()  
		if(c <= (20 * timeF)):
			c = c + 1
		else:
			vc.release()
		cv2.waitKey(1)
	#print("Input 'q' to quit!")
	
def start_video():
	while True:
		value = input("Input 's' start video:")
		if value == 's':
			anaoshots()
		elif value == 'q':
			break
			

start_video()


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值