python opencv通过按键采集图片源码


Posted in Python onMay 20, 2021

一、python版本

写了个python opencv的小demo,可以通过键盘按下字母s进行采集图像。

功能说明

“N” 新建文件夹 data/ 用来存储图像
“S” 开始采集图像,将采集到的图像放到 data/ 路径下
“Q” 退出窗口

python opencv源码

'''

“N”  新建文件夹 data/  用来存储图像
"S"   开始采集图像,将采集到的图像放到 data/ 路径下
“Q”   退出窗口
'''

import numpy as np  # 数据处理的库 Numpy
import cv2          # 图像处理的库 OpenCv
import os           # 读写文件
import shutil       # 读写文件
from PIL import Image, ImageDraw, ImageFont


# # OpenCv 调用摄像头 / Use camera
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH,1920)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,1080)

'''
#功能函数,只是用来往图片中显示汉字
#示例 img = cv2ImgAddText(cv2.imread('img1.jpg'), "大家好,我是片天边的云彩", 10, 65, (0, 0, 139), 20)
参数说明:
img:OpenCV图片格式的图片
text:要写入的汉字
left:字符坐标x值
top:字符坐标y值
textColor:字体颜色
:textSize:字体大小
'''
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        "font/simsun.ttc", textSize, encoding="utf-8")
    # 绘制文本
    draw.text((left, top), text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)

# 存储图像的文件夹 
current_dir = ""
# 保存  图像 的路径 
path_photos_from_camera = "data/"

press_n_flag = 0
cnt_ss=0



while cap.isOpened():
    flag, img_rd = cap.read()
    #print(img_rd.shape)

    kk = cv2.waitKey(2)
    # 待会要写的字体 / Font to write
    font = cv2.FONT_ITALIC

    # 4. 按下 'n' 新建存储人脸的文件夹 / press 'n' to create the folders for saving faces
    if kk == ord('N') or kk == ord('n'):
        current_dir = path_photos_from_camera
        #os.makedirs(current_dir)
        if os.path.isdir(current_dir):
            pass
        else:
            os.mkdir(current_dir)
        print('\n')
        print("新建的保存图像的文件夹 / Create folders: ", current_dir)

        press_n_flag = 1        # 已经按下 'n' / have pressed 'n'


    # 5. 按下 's' 保存摄像头中的图像到本地 / Press 's' to save image into local images
    if kk == ord('S') or kk == ord('s'):
        # 检查有没有先按'n'新建文件夹 / check if you have pressed 'n'
        if press_n_flag:
            cnt_ss += 1
            cv2.imwrite(current_dir + "/img_" + str(cnt_ss) + ".jpg", img_rd)
            print("写入本地 / Save into:", str(current_dir) + "/img_face_" + str(cnt_ss) + ".jpg")
        else:
            print("请在按 'S' 之前先按 'N' 来建文件夹 / Please press 'N' before 'S'")


    # 添加说明 / Add some statements
    #cv2.putText(img_rd, "Face Register", (20, 40), font, 1, (0, 255, 0), 1, cv2.LINE_AA)
    img_rd = cv2ImgAddText(img_rd, "图片采集系统", 160, 25, (0, 255,0), 30)
    #cv2.putText(img_rd, "N: Create face folder", (20, 350), font, 0.8, (0, 255, 0), 1, cv2.LINE_AA)
    img_rd = cv2ImgAddText(img_rd, "N: 创建保存图像文件夹", 20, 350, (0, 255, 0), 20)
    #cv2.putText(img_rd, "S: Save current face", (20, 400), font, 0.8, (0, 255, 0), 1, cv2.LINE_AA)
    img_rd = cv2ImgAddText(img_rd, "S: 保存当前图片", 20, 400, (0, 255, 0), 20)
    #cv2.putText(img_rd, "Q: Quit", (20, 450), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)
    img_rd = cv2ImgAddText(img_rd, "Q: 退出", 20, 450, (0, 255, 0), 20)

    # 6. 按下 'Q' 键退出 / Press 'q' to exit
    if kk == ord('Q') or kk == ord('q'):
        break
    # 如果需要摄像头窗口大小可调 / Uncomment this line if you want the camera window is resizeable
    cv2.namedWindow("camera", 0)
    cv2.imshow("camera", img_rd)

# 释放摄像头 / Release camera and destroy all windows
cap.release()
cv2.destroyAllWindows()

效果图

python opencv通过按键采集图片源码

安装相关库

windows安装

pip install pillow

tx2/linux/…

sudo apt-get install python3-pillow

二、c语言版本

 c语言源码

/*****************************************************
2021.5.18:按键采集图像
******************************************************/
#include "opencv2/core/core.hpp"    
#include "opencv2/imgproc/imgproc.hpp"    
#include "opencv2/calib3d/calib3d.hpp"    
#include "opencv2/highgui/highgui.hpp"    
#include <iostream>    
#include <fstream>    

using namespace cv;
using namespace std;

#define SRC_WIDTH  1920
#define SRC_HEIGHT 1080

int main()
{
	//测试视频
	VideoCapture capture;
	capture.open(1);
	//capture.open("v4l2src device=/dev/video4 ! video/x-raw,width=1920,height=1020,framerate=30/1 ! videoconvert ! appsink");
	if (!capture.isOpened())
	{
		printf("文件打开失败");
	}
	capture.set(CAP_PROP_FRAME_WIDTH, SRC_WIDTH);        //设置宽度
	capture.set(CAP_PROP_FRAME_HEIGHT, SRC_HEIGHT);  //设置长度
	Mat frame;
	int n = 0;
	char* cstr = new char[120];
	while (true)
	{
		
		capture >> frame;
		if (frame.data == NULL)
		{
			printf("Image is empty\n");
			//writer.write(frame);
			break;
			//continue;
		}
		char kk=waitKey(2);
		if (kk == 'S' || kk == 's')
		{

			sprintf(cstr, "%s%d%s", "caliberation/", n++, ".jpg");
			imwrite(cstr, frame);
			printf("保存了图片\n");

		}

		
		namedWindow("111", 0);//参数为零,则可以自由拖动
		imshow("111", frame);
		waitKey(2);
	}

	return 0;

}

效果图

python opencv通过按键采集图片源码

到此这篇关于opencv通过按键采集图片源码的文章就介绍到这了,更多相关opencv按键采集图片内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python通过解析网页实现看报程序的方法
Aug 04 Python
解决win64 Python下安装PIL出错问题(图解)
Sep 03 Python
Python Flask 搭建微信小程序后台详解
May 06 Python
500行Python代码打造刷脸考勤系统
Jun 03 Python
用python wxpy管理微信公众号并利用微信获取自己的开源数据
Jul 30 Python
django之自定义软删除Model的方法
Aug 14 Python
利用python、tensorflow、opencv、pyqt5实现人脸实时签到系统
Sep 25 Python
Django调用百度AI接口实现人脸注册登录代码实例
Apr 23 Python
Python reduce函数作用及实例解析
May 08 Python
基于opencv的selenium滑动验证码的实现
Jul 24 Python
Python xmltodict模块安装及代码实例
Oct 05 Python
简单且有用的Python数据分析和机器学习代码
Jul 02 Python
python 如何执行控制台命令与操作剪切板
教你怎么用Python生成九宫格照片
用 Python 元类的特性实现 ORM 框架
May 19 #Python
浅谈Python 中的复数问题
May 19 #Python
Python机器学习之基础概述
Python机器学习之PCA降维算法详解
Python 批量下载阴阳师网站壁纸
May 19 #Python
You might like
解析在PHP中使用全局变量的几种方法
2013/06/24 PHP
PHP函数实现从一个文本字符串中提取关键字的方法
2015/07/01 PHP
自定义min版smarty模板引擎MinSmarty.class.php文件及用法
2016/05/20 PHP
PHP框架Laravel中使用UUID实现数据分表操作示例
2018/05/30 PHP
yii 框架实现按天,月,年,自定义时间段统计数据的方法分析
2020/04/04 PHP
jquery 获取json数据实现代码
2009/04/27 Javascript
无闪烁更新网页内容JS实现
2013/12/19 Javascript
js实现省市联动效果的简单实例
2014/02/10 Javascript
JS使用正则表达式除去字符串中重复字符的方法
2015/11/05 Javascript
浅谈javascript 函数表达式和函数声明的区别
2016/01/05 Javascript
html5+javascript实现简单上传的注意细节
2016/04/18 Javascript
js实现网页定位导航功能
2017/03/07 Javascript
vue中导出Excel表格的实现代码
2018/10/18 Javascript
JavaScript检测浏览器是否支持CSS变量代码实例
2020/04/03 Javascript
[51:17]Mineski vs Secret 2019国际邀请赛淘汰赛 败者组 BO3 第一场 8.22
2019/09/05 DOTA
python根据开头和结尾字符串获取中间字符串的方法
2015/03/26 Python
python使用MySQLdb访问mysql数据库的方法
2015/08/03 Python
浅谈pandas中Dataframe的查询方法([], loc, iloc, at, iat, ix)
2018/04/10 Python
使用python脚本实现查询火车票工具
2018/07/19 Python
python实现高斯判别分析算法的例子
2019/12/09 Python
Python压缩模块zipfile实现原理及用法解析
2020/08/14 Python
德购商城:德国进口直邮商城
2017/06/13 全球购物
澳大利亚设计的婴儿和女孩的衣服:Oobi
2018/12/16 全球购物
什么情况下你必须要把一个类定义为abstract的
2013/01/06 面试题
高级技校毕业生自荐信
2013/11/18 职场文书
司法局火灾防控方案
2014/06/05 职场文书
十佳标兵事迹材料
2014/08/18 职场文书
营销与策划实训报告
2014/11/05 职场文书
村级干部党员公开承诺事项
2015/05/04 职场文书
2015年前台接待工作总结
2015/05/04 职场文书
2015年党建工作目标责任书
2015/05/08 职场文书
同乡会致辞
2015/07/30 职场文书
学校食堂管理制度
2015/08/04 职场文书
my.ini优化mysql数据库性能的十个参数(推荐)
2021/05/26 MySQL
golang特有程序结构入门教程
2021/06/02 Python
Windows Server 版本 20H2 于 8 月 9 日停止支持,Win10 版本 21H1 将于 12 月结束支
2022/07/23 数码科技