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生成XML的方法实例
Mar 21 Python
基于Django的python验证码(实例讲解)
Oct 23 Python
mac安装pytorch及系统的numpy更新方法
Jul 26 Python
CentOS 7 安装python3.7.1的方法及注意事项
Nov 01 Python
使用python动态生成波形曲线的实现
Dec 04 Python
tensorflow实现tensor中满足某一条件的数值取出组成新的tensor
Jan 04 Python
Python Socketserver实现FTP文件上传下载代码实例
Mar 27 Python
解决安装新版PyQt5、PyQT5-tool后打不开并Designer.exe提示no Qt platform plugin的问题
Apr 24 Python
PyTorch的torch.cat用法
Jun 28 Python
如何在python中实现线性回归
Aug 10 Python
Python虚拟环境的创建和使用详解
Sep 07 Python
python中random模块详解
Mar 01 Python
python 如何执行控制台命令与操作剪切板
教你怎么用Python生成九宫格照片
用 Python 元类的特性实现 ORM 框架
May 19 #Python
浅谈Python 中的复数问题
May 19 #Python
Python机器学习之基础概述
Python机器学习之PCA降维算法详解
Python 批量下载阴阳师网站壁纸
May 19 #Python
You might like
Flash空降上海 化身大魔王接受挑战
2020/03/02 星际争霸
一些需要禁用的PHP危险函数(disable_functions)
2012/02/23 PHP
关于js与php互相传值的介绍
2013/06/25 PHP
在第一个input框内输入内容.textarea自动得到第一个文件框的值的javascript代码
2007/04/20 Javascript
js 无提示关闭浏览器页面的代码
2010/03/09 Javascript
Microsfot .NET Framework4.0框架 安装失败的解决方法
2013/08/14 Javascript
js判断两个日期是否相等的方法
2013/09/10 Javascript
利用try-catch判断变量是已声明未声明还是未赋值
2014/03/12 Javascript
AngularJS入门(用ng-repeat指令实现循环输出
2016/05/05 Javascript
微信开发 使用picker封装省市区三级联动模板
2016/10/28 Javascript
JS正则表达式验证账号、手机号、电话和邮箱是否合法
2017/03/08 Javascript
简述Angular 5 快速入门
2017/11/04 Javascript
Vue导出json数据到Excel电子表格的示例
2017/12/04 Javascript
Vue2.5通过json文件读取数据的方法
2018/02/27 Javascript
JS中promise化微信小程序api
2018/04/12 Javascript
iview Upload组件多个文件上传的示例代码
2018/09/30 Javascript
JavaScript设计模式---单例模式详解【四种基本形式】
2020/05/16 Javascript
vue-model实现简易计算器
2020/08/17 Javascript
利用Python演示数型数据结构的教程
2015/04/03 Python
python 随机生成10位数密码的实现代码
2019/06/27 Python
Python实现桌面翻译工具【新手必学】
2020/02/12 Python
css3实现超炫风车特效
2014/11/12 HTML / CSS
Ray-Ban雷朋太阳眼镜英国官网:Ray-Ban UK
2019/11/23 全球购物
金融专业推荐信
2013/11/14 职场文书
医学专业五年以上个人求职信
2013/12/03 职场文书
网络优化专员求职信
2014/05/04 职场文书
爱国口号
2014/06/19 职场文书
工作说明书格式
2014/07/29 职场文书
干部竞争上岗演讲稿
2014/09/11 职场文书
2014年学习部工作总结
2014/11/12 职场文书
大学生考试作弊被抓检讨书
2014/12/27 职场文书
2015年安全生产管理工作总结
2015/05/25 职场文书
禁毒心得体会范文
2016/01/15 职场文书
如何有效防止sql注入的方法
2021/05/25 SQL Server
MySQL数据库必备之条件查询语句
2021/10/15 MySQL
分析SQL窗口函数之取值窗口函数
2022/04/21 Oracle