首页
实用工具
我的旅程
在线壁纸
更多
✒️ 问题反馈
📦 文章统计
🌍 国内镜像
🎬 次元视界
📒 流水账本
🎨 在线 PS
推荐
🕵️ 开源情报
🌆 图片压缩
🍭 资产清洗
💡 我的作品
👤 关于站长
⚔️ 次 元 剑
搜索
1
【工具分享】逆向工具箱 - 次元剑
89,538 阅读
2
【技术分享】PE文件结构分析 ( RVA转FOA )
7,350 阅读
3
【技术分享】NASM x86 Assembly Language
5,982 阅读
4
【技术分享】CK竞技之王游戏辅助制作
3,725 阅读
5
【每日随记】天涯明月刀无限飞修改思路
2,816 阅读
技术分享
CTF解题
英语笔记
数学笔记
网络通信
每日随记
攻防技术
工具分享
Search
标签搜索
Windows
Web安全
Python3
Linux
逆向工程
CTF
红队技术
人工智能
C/C++
黑客工具
Go
密码学
二进制安全
数学
漏洞挖掘
Android
eNSP
渗透测试
蓝队技术
黑客大会
发光的神
累计撰写
160
篇文章
累计收到
103
条评论
首页
栏目
技术分享
CTF解题
英语笔记
数学笔记
网络通信
每日随记
攻防技术
工具分享
页面
实用工具
我的旅程
在线壁纸
✒️ 问题反馈
📦 文章统计
🌍 国内镜像
🎬 次元视界
📒 流水账本
🎨 在线 PS
推荐
🕵️ 开源情报
🌆 图片压缩
🍭 资产清洗
💡 我的作品
👤 关于站长
⚔️ 次 元 剑
搜索到
19
篇与
的结果
2022-09-13
【技术分享】Python3 文字识别模型训练
简介Torch 是一种常用的深度学习框架,可以用于训练各种类型的神经网络模型,包括文字识别模型,文字识别模型是一种能够自动识别图像中的文字并将其转换成可编辑文本的模型,在训练模型之前,准备好一组包含大量图像和相应标签的数据集,Torch 中提供的工具和函数,可以构建、训练和测试一个文字识别模型,在模型训练完成后,可以将其用于对新的图像进行文字识别,并输出识别结果。训练代码import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision from torchvision import datasets, transforms import matplotlib.pyplot as plt # 默认显示512张图片 BATCH_SIZE = 512 # 默认训练批次20次 EPOCHS = 20 # 默认使用cpu加速 DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") # 构建数据转换列表 tsfrm = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1037,), (0.3081,)) ]) # 由于官方已经实现dataset,直接使用DataLoader来获取数据 # MNIST数据集包含6万张28x28的训练样本,1万张测试样本 # 下载训练集 train_loader = torch.utils.data.DataLoader( datasets.MNIST(root = 'data', train = True, download = True, transform = tsfrm), batch_size = BATCH_SIZE, shuffle = True) # 下载测试集 test_loader = torch.utils.data.DataLoader( datasets.MNIST(root = 'data', train = False, download = True, transform = tsfrm), batch_size = BATCH_SIZE, shuffle = True) # 展示训练样本图片 # 使用torchvision.utils中的make_grid类方法将一个批次的图片构造成网格模式 def imshow(images): img = torchvision.utils.make_grid(images) npimg = img.numpy() plt.imshow(np.transpose(npimg,(1,2,0))) plt.show() # 从训练集中拿出一批图像 # 用iter和next函数来获取取一个批次的图片数据和其对应的图片标签 images,labels = next(iter(train_loader)) imshow(images) print(labels) # 定义一个LeNet-5网络,包含两个卷积层conv1和conv2,两个线性层作为输出,最后输出10个维度 # 这10个维度作为0-9的标识来确定识别出的是哪个数字。 class ConvNet(nn.Module): def __init__(self): super().__init__() # 1*1*28*28 # 1个输入图片通道,10个输出通道,5x5卷积核 self.conv1 = nn.Conv2d(1, 10, 5) self.conv2 = nn.Conv2d(10, 20, 3) # 全连接层、输出层softmax,10个维度 self.fc1 = nn.Linear(20 * 10 * 10, 500) self.fc2 = nn.Linear(500, 10) # 正向传播 def forward(self, x): in_size = x.size(0) out = self.conv1(x) # 1* 10 * 24 *24 out = F.relu(out) out = F.max_pool2d(out, 2, 2) # 1* 10 * 12 * 12 out = self.conv2(out) # 1* 20 * 10 * 10 out = F.relu(out) out = out.view(in_size, -1) # 1 * 2000 out = self.fc1(out) # 1 * 500 out = F.relu(out) out = self.fc2(out) # 1 * 10 out = F.log_softmax(out, dim=1) return out # 生成模型 model = ConvNet().to(DEVICE) print(model) # 构建优化器optimizer,包含一个可进行迭代优化的、包含所有参数的列表 # model.parameters()表示优化的参数,lr表示学习率 optimizer = optim.Adam(model.parameters(),lr=0.0001) # 定义训练函数 def train(model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): # 输入样本和标签 data, target = data.to(device), target.to(device) # 每次训练梯度清零 optimizer.zero_grad() # 正向传播、反向传播和优化过程 output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() # 打印训练情况 if (batch_idx + 1) % 30 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) # 定义验证函数 def test(model, device, test_loader): model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: # 输入样本和标签 data, target = data.to(device), target.to(device) output = model(data) # 将一批的损失相加 test_loss += F.nll_loss(output, target, reduction='sum') # 找到概率最大的下标 pred = output.max(1, keepdim=True)[1] correct += pred.eq(target.view_as(pred)).sum().item() test_loss /= len(test_loader.dataset) # 打印验证情况 print("\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%) \n".format( test_loss, correct, len(test_loader.dataset), 100. * correct / len(test_loader.dataset) )) # 开始训练模型 for epoch in range(1, EPOCHS + 1): train(model, DEVICE, train_loader, optimizer, epoch) test(model, DEVICE, test_loader) # 保存模型 torch.save(model.state_dict(), "./MNISTModel.pkl")识别代码import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision from torchvision import datasets, transforms # 默认预测四张含有数字的图片 BATCH_SIZE = 4 # 默认使用cpu加速 DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") # 构建数据转换列表 tsfrm = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1037,), (0.3081,)) ]) # 测试集 test_loader = torch.utils.data.DataLoader( datasets.MNIST(root='data', train=False, download=True, transform=tsfrm), batch_size=BATCH_SIZE, shuffle=True) # 定义图片可视化函数 def imshow(images): img = torchvision.utils.make_grid(images) img = img.numpy().transpose(1, 2, 0) std = [0.5, 0.5, 0.5] mean = [0.5, 0.5, 0.5] img = img * std + mean # 将图片高和宽分别赋值给x1,y1 x1, y1 = img.shape[0:2] # 图片放大到原来的5倍,输出尺寸格式为(宽,高) enlarge_img = cv2.resize(img, (int(y1*5), int(x1*5))) cv2.imshow('image', enlarge_img) cv2.waitKey(0) # 定义一个LeNet-5网络,包含两个卷积层conv1和conv2,两个线性层作为输出,最后输出10个维度 # 这10个维度作为0-9的标识来确定识别出的是哪个数字。 class ConvNet(nn.Module): def __init__(self): super().__init__() # 1*1*28*28 # 1个输入图片通道,10个输出通道,5x5卷积核 self.conv1 = nn.Conv2d(1, 10, 5) self.conv2 = nn.Conv2d(10, 20, 3) # 全连接层、输出层softmax,10个维度 self.fc1 = nn.Linear(20 * 10 * 10, 500) self.fc2 = nn.Linear(500, 10) # 正向传播 def forward(self, x): in_size = x.size(0) out = self.conv1(x) # 1* 10 * 24 *24 out = F.relu(out) out = F.max_pool2d(out, 2, 2) # 1* 10 * 12 * 12 out = self.conv2(out) # 1* 20 * 10 * 10 out = F.relu(out) out = out.view(in_size, -1) # 1 * 2000 out = self.fc1(out) # 1 * 500 out = F.relu(out) out = self.fc2(out) # 1 * 10 out = F.log_softmax(out, dim=1) return out # 主程序入口 if __name__ == "__main__": model_eval = ConvNet() # 加载训练模型 model_eval.load_state_dict(torch.load( './MNISTModel.pkl', map_location=DEVICE)) model_eval.eval() # 从测试集里面拿出几张图片 images, labels = next(iter(test_loader)) inputs = images.to(DEVICE) # 输出 outputs = model_eval(inputs) # 找到概率最大的下标 _, preds = torch.max(outputs, 1) # 打印预测结果 numlist = [] for i in range(len(preds)): label = preds.numpy()[i] numlist.append(label) List = ' '.join(repr(s) for s in numlist) print('当前预测的数字为: ', List) # 显示图片 imshow(images)识别效果
2022年09月13日
35 阅读
1 评论
5 点赞
2022-07-23
【技术分享】Python3 屏幕单目标跟踪 opencv + dlib实现 ( 第六课 )
简介dlib提供了dlib.correlation_tracker()类用于跟踪目标,于是自己修改了下直接在屏幕上绘制识别物体,效果一般有时识别会出错。完整代码import cv2 import numpy as np import dlib, mss, os window_name = 'Testone' window_size = 2 sct = mss.mss() screen_width = 1920 screen_height = 1080 # win_left , win_top, win_width, win_height = screen_width // 3, screen_height // 3, screen_width // 3, screen_height // 3 rwidth, rheight = screen_width // window_size, screen_height // window_size monitor = { 'left': 0, 'top': 0, 'width': 1920, 'height': 1080, } tracker = dlib.correlation_tracker() start_flag = True selection = None track_window = None drag_start = None def onMouseClicked(event, x, y, flags, param): global selection, track_window, drag_start if event == cv2.EVENT_LBUTTONDOWN: drag_start = (x, y) track_window = None if drag_start: xMin = min(x, drag_start[0]) yMin = min(y, drag_start[1]) xMax = max(x, drag_start[0]) yMax = max(y, drag_start[1]) selection = (xMin, yMin, xMax, yMax) if event == cv2.EVENT_LBUTTONUP: drag_start = None track_window = selection selection = None cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) cv2.resizeWindow(window_name, rwidth, rheight) cv2.setMouseCallback(window_name, onMouseClicked) while True: try: img = sct.grab(monitor=monitor) img = np.array(img) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if start_flag == True: while True: img_first = img.copy() if track_window: cv2.rectangle(img_first, (track_window[0], track_window[1]), (track_window[2], track_window[3]), (255,255,255), 2) elif selection: cv2.rectangle(img_first, (selection[0], selection[1]), (selection[2], selection[3]), (255,255,255), 2) cv2.imshow(window_name, img_first) if cv2.waitKey(5) == 13: break start_flag = False tracker.start_track(gray, dlib.rectangle(track_window[0], track_window[1], track_window[2], track_window[3])) else: tracker.update(gray) box_predict = tracker.get_position() cv2.rectangle(img,(int(box_predict.left()),int(box_predict.top())),(int(box_predict.right()),int(box_predict.bottom())),(0,255,255),2) cv2.imshow(window_name, img) if cv2.waitKey(10) == 27: break except Exception as e: print(e) os._exit(0) cv2.destroyAllWindows()视频效果{dplayer src="https://www.52tt.pro/usr/uploads/2022/11/11.13.mp4"/}
2022年07月23日
62 阅读
0 评论
4 点赞
2022-07-22
【技术分享】Python3 模型训练与预测 opencv + dlib实现 ( 第五课 )
训练代码import dlib import cv2 as cv def Train(): options = dlib.simple_object_detector_training_options() options.add_left_right_image_flips = True options.C = 5 options.num_threads = 2 options.be_verbose = True dlib.train_simple_object_detector('data.xml', 'data.svm', options) def deteTest(): imgpath = '1.png' image = cv.imread(imgpath) gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) detector = dlib.simple_object_detector("data.svm") dets = detector(gray) for (k, d) in enumerate(dets): cv.rectangle(image, (d.left(), d.top()), (d.left() + d.width(), d.top() + d.height()), (0, 255, 0), 1) cv.imshow("Output", image) cv.waitKey(0) if __name__ == '__main__': while True: print(''' | 1.训练模型 | 2.查看效果 | '''.strip()) var = int(input(">>")) if var == 1: Train() if var == 2: deteTest()检测代码import cv2 as cv import numpy as np import dlib, mss, os window_name = 'Test' window_size = 2 sct = mss.mss() monitor = { 'left': 0, 'top': 0, 'width': 1920, 'height': 1080, } num_res_width = 1920 // 2 num_res_height = 1080 // 2 while True: try: # hwnds = win32gui.FindWindow('Chrome_WidgetWin_1', None) # left, top, right, bottom = win32gui.GetWindowRect(hwnds) img = sct.grab(monitor=monitor) img = np.array(img) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) cv.namedWindow(window_name, cv.WINDOW_NORMAL) cv.resizeWindow(window_name, num_res_width, num_res_height) detector = dlib.get_frontal_face_detector() dets = detector(gray) for _, d in enumerate(dets): cv.rectangle(img, (d.left(), d.top()), (d.left() + d.width(), d.top() + d.height()), (0, 0, 255), 2) cv.putText(img, "1", (d.left() + d.width(), d.top() + d.height()), cv.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 2) cv.imshow(window_name, img) k = cv.waitKey(1) if k % 256 == 27: cv.destroyAllWindows() exit('已退出...') except Exception as e: print(e) os._exit(0)视频教程{bilibili bvid="BV16T4y1r7Jj" page=""/}{cloud title="训练工具" type="default" url="https://wws.lanzouj.com/iEbAK07u66oj" password=""/}
2022年07月22日
411 阅读
0 评论
125 点赞
2022-07-22
【技术分享】Python3 比对人脸 opencv + dlib实现 ( 第四课 )
简介在前面的几课中介绍了,如何使用dlib标定人脸 人脸检测 提取68个特征点。这次要在这两个工作的基础之上,将人脸的信息提取成一个128维的向量空间。在这个向量空间上,同一个人脸的更接近,不同人脸的距离更远。度量采用欧式距离,欧氏距离计算不算复杂。二维公式三维公式将其扩展到128维的情况下通常使用的判别阈值是0.6,即如果两个人脸的向量空间的欧式距离超过了0.6,即认定不是同一个人;如果欧氏距离小于0.6,则认为是同一个人。{cloud title="模型下载" type="bd" url="https://www.123684.com/s/Ke1Jjv-31go3" password=""/}完整代码import cv2 import dlib import numpy as np def main(): img1 = cv2.imread("1.jpeg") img2 = cv2.imread("2.jpeg") test = cv2.imread("test.jpeg") # BGR to RGB img1 = img1[:, :, ::-1] img2 = img2[:, :, ::-1] test = test[:, :, ::-1] detector = load_face_detector() predictor = load_key_detector() encoder = load_face_coding_feature_model() img1_128D = encoder_face(img1,detector,predictor,encoder)[0] img2_128D = encoder_face(img2,detector,predictor,encoder)[0] test_128D = encoder_face(test,detector,predictor,encoder)[0] all_image_128D = [img1_128D, img2_128D] distance =compare_faces(all_image_128D,test_128D) print(distance) # 加载人脸检测器 def load_face_detector(): return dlib.get_frontal_face_detector() # 加载关键点模型 def load_key_detector(): return dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # 加载人脸编码特征模型 def load_face_coding_feature_model(): return dlib.face_recognition_model_v1("dlib_face_recognition_resnet_model_v1.dat") # 关键点编码为128D def encoder_face(image,detector,predictor,encoder,upsample=1,jet=1): # 检测人脸(检测到几张人脸) faces = detector(image,upsample) # 对检测的人脸进行关键点检测 faces_key_points = [predictor(image,face) for face in faces] # 对每张检测点进行128D return [np.array(encoder.compute_face_descriptor(image,faces_key_point,jet)) for faces_key_point in faces_key_points] # 人脸比较,通过欧式距离 def compare_faces(face_encoding, test_encoding): return list(np.linalg.norm(np.array(face_encoding) - np.array(test_encoding), axis=1)) if __name__ == '__main__': main() {lamp/}
2022年07月22日
263 阅读
2 评论
68 点赞
2022-07-22
【技术分享】Python3 单目标跟踪 opencv + dlib实现 ( 第三课 )
简介dlib提供了dlib.correlation_tracker()类用于跟踪目标,效果一般般,没训练的模型好。官方文档入口:http://dlib.net/python/index.html#dlib.correlation_tracker完整源码(直接绘制完成后按下enter键即可跟踪)import sys import dlib import cv2 tracker = dlib.correlation_tracker() # 导入correlation_tracker()类 cap = cv2.VideoCapture(0) # OpenCV打开摄像头 start_flag = True # 标记,是否是第一帧,若在第一帧需要先初始化 selection = None # 实时跟踪鼠标的跟踪区域 track_window = None # 要检测的物体所在区域 drag_start = None # 标记,是否开始拖动鼠标 # 鼠标点击事件回调函数 def onMouseClicked(event, x, y, flags, param): global selection, track_window, drag_start # 定义全局变量 if event == cv2.EVENT_LBUTTONDOWN: # 鼠标左键按下 drag_start = (x, y) track_window = None if drag_start: # 是否开始拖动鼠标,记录鼠标位置 xMin = min(x, drag_start[0]) yMin = min(y, drag_start[1]) xMax = max(x, drag_start[0]) yMax = max(y, drag_start[1]) selection = (xMin, yMin, xMax, yMax) if event == cv2.EVENT_LBUTTONUP: # 鼠标左键松开 drag_start = None track_window = selection selection = None cv2.namedWindow("image", cv2.WINDOW_AUTOSIZE) cv2.setMouseCallback("image", onMouseClicked) # opencv的bgr格式图片转换成rgb格式 # b, g, r = cv2.split(frame) # frame2 = cv2.merge([r, g, b]) while True: ret, frame = cap.read() # 从摄像头读入1帧 if start_flag == True: # 如果是第一帧,需要先初始化 # 这里是初始化,窗口中会停在当前帧,用鼠标拖拽一个框来指定区域,随后会跟踪这个目标;我们需要先找到目标才能跟踪不是吗? while True: img_first = frame.copy() # 不改变原来的帧,拷贝一个新的出来 if track_window: # 跟踪目标的窗口画出来了,就实时标出来 cv2.rectangle(img_first, (track_window[0], track_window[1]), (track_window[2], track_window[3]), (0,0,255), 1) elif selection: # 跟踪目标的窗口随鼠标拖动实时显示 cv2.rectangle(img_first, (selection[0], selection[1]), (selection[2], selection[3]), (0,0,255), 1) cv2.imshow("image", img_first) # 按下回车,退出循环 if cv2.waitKey(5) == 13: break start_flag = False # 初始化完毕,不再是第一帧了 tracker.start_track(frame, dlib.rectangle(track_window[0], track_window[1], track_window[2], track_window[3])) # 跟踪目标,目标就是选定目标窗口中的 else: tracker.update(frame) # 更新,实时跟踪 box_predict = tracker.get_position() # 得到目标的位置 cv2.rectangle(frame,(int(box_predict.left()),int(box_predict.top())),(int(box_predict.right()),int(box_predict.bottom())),(0,255,255),1) # 用矩形框标注出来 cv2.imshow("image", frame) # 如果按下ESC键,就退出 if cv2.waitKey(10) == 27: break cap.release() cv2.destroyAllWindows() 视频效果隐藏内容,请前往内页查看详情官方示例# The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt # # This example shows how to use the correlation_tracker from the dlib Python # library. This object lets you track the position of an object as it moves # from frame to frame in a video sequence. To use it, you give the # correlation_tracker the bounding box of the object you want to track in the # current video frame. Then it will identify the location of the object in # subsequent frames. # # In this particular example, we are going to run on the # video sequence that comes with dlib, which can be found in the # examples/video_frames folder. This video shows a juice box sitting on a table # and someone is waving the camera around. The task is to track the position of # the juice box as the camera moves around. # # # COMPILING/INSTALLING THE DLIB PYTHON INTERFACE # You can install dlib using the command: # pip install dlib # # Alternatively, if you want to compile dlib yourself then go into the dlib # root folder and run: # python setup.py install # or # python setup.py install --yes USE_AVX_INSTRUCTIONS # if you have a CPU that supports AVX instructions, since this makes some # things run faster. # # Compiling dlib should work on any operating system so long as you have # CMake and boost-python installed. On Ubuntu, this can be done easily by # running the command: # sudo apt-get install libboost-python-dev cmake # # Also note that this example requires scikit-image which can be installed # via the command: # pip install scikit-image # Or downloaded from http://scikit-image.org/download.html. import os import glob import dlib from skimage import io # Path to the video frames video_folder = os.path.join("..", "examples", "video_frames") # Create the correlation tracker - the object needs to be initialized # before it can be used tracker = dlib.correlation_tracker() win = dlib.image_window() # We will track the frames as we load them off of disk for k, f in enumerate(sorted(glob.glob(os.path.join(video_folder, "*.jpg")))): print("Processing Frame {}".format(k)) img = io.imread(f) # We need to initialize the tracker on the first frame if k == 0: # Start a track on the juice box. If you look at the first frame you # will see that the juice box is contained within the bounding # box (74, 67, 112, 153). tracker.start_track(img, dlib.rectangle(74, 67, 112, 153)) else: # Else we just attempt to track from the previous frame tracker.update(img) win.clear_overlay() win.set_image(img) win.add_overlay(tracker.get_position()) dlib.hit_enter_to_continue(){dotted startColor="#ff6c6c" endColor="#1989fa"/}
2022年07月22日
123 阅读
0 评论
50 点赞
2022-07-21
【技术分享】Python3 人脸特征点标定 opencv + dlib实现 ( 第二课 )
简介在我们检测到人脸区域之后,接下来要研究的问题是获取到不同的脸部的特征,以区分不同人脸,即人脸特征检测(facial feature detection)。它也被称为人脸特征点检测(facial landmark detection)。人脸特征点通常会标识出脸部的下列数个区域:右眼眉毛(Right eyebrow)左眼眉毛(Left eyebrow)右眼(Right eye)左眼(Left eye)嘴巴(Mouth)鼻子(Nose)下巴(Jaw)dlib提供了训练好的模型,可以识别人脸的68个特征点{cloud title="68特征数据" type="bd" url="https://www.123684.com/s/Ke1Jjv-h1go3" password=""/} import dlib import cv2 # 使用 Dlib 的正面人脸检测器 frontal_face_detector detector = dlib.get_frontal_face_detector() # Dlib 的 68点模型 predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # 读取图片 img = cv2.imread("2.jpeg") # 生成 Dlib 的图像窗口 win = dlib.image_window() win.set_image(img) # 使用 detector 检测器来检测图像中的人脸 faces = detector(img, 1) print("人脸数:", len(faces)) for i, d in enumerate(faces): print("第", i+1, "个人脸的矩形框坐标:", "left:", d.left(), "right:", d.right(), "top:", d.top(), "bottom:", d.bottom()) # 使用predictor来计算面部轮廓 shape = predictor(img, faces[i]) # 绘制面部轮廓 win.add_overlay(shape) # 绘制矩阵轮廓 win.add_overlay(faces) dlib.hit_enter_to_continue()完整示例:import cv2 import dlib # 读取图片 img_path = "1.jpeg" img = cv2.imread(img_path) # 转换为灰阶图片 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 正向人脸检测器 detector = dlib.get_frontal_face_detector() # 使用训练完成的68个特征点模型 predictor_path = "shape_predictor_68_face_landmarks.dat" predictor = dlib.shape_predictor(predictor_path) # 使用检测器来检测图像中的人脸 faces = detector(gray, 1) for i, face in enumerate(faces): # 获取人脸特征点 shape = predictor(img, face) # 遍历所有点 for pt in shape.parts(): # 绘制特征点 pt_pos = (pt.x, pt.y) cv2.circle(img, pt_pos, 1, (255,0, 0), 2) cv2.imshow('opencv_face_laowang',img) # 显示图片 cv2.waitKey(0) # 等待用户关闭图片窗口 cv2.destroyAllWindows()# 关闭窗口{lamp/}
2022年07月21日
85 阅读
0 评论
20 点赞
2022-07-13
【技术分享】Python3 人脸检测 opencv + dlib实现 ( 第一课 )
简介dlib是一个很有名的库,有c++、Python的接口。使用dlib可以大大简化开发,比如人脸识别,特征点检测之类的工作都可以很轻松实现。同时也有很多基于dlib开发的应用和开源库,比如face_recogintion库(应用一个基于Python的开源人脸识别库,face_recognition)等等。参考代码import sys import dlib import cv2 detector = dlib.get_frontal_face_detector() #获取人脸分类器 # 传入的命令行参数 for f in sys.argv[1:]: # opencv 读取图片,并显示 img = cv2.imread(f, cv2.IMREAD_COLOR) # 摘自官方文档: # image is a numpy ndarray containing either an 8bit grayscale or RGB image. # opencv读入的图片默认是bgr格式,我们需要将其转换为rgb格式;都是numpy的ndarray类。 b, g, r = cv2.split(img) # 分离三个颜色通道 img2 = cv2.merge([r, g, b]) # 融合三个颜色通道生成新图片 dets = detector(img, 1) #使用detector进行人脸检测 dets为返回的结果 print("Number of faces detected: {}".format(len(dets))) # 打印识别到的人脸个数 # enumerate是一个Python的内置方法,用于遍历索引 # index是序号;face是dets中取出的dlib.rectangle类的对象,包含了人脸的区域等信息 # left()、top()、right()、bottom()都是dlib.rectangle类的方法,对应矩形四条边的位置 for index, face in enumerate(dets): print('face {}; left {}; top {}; right {}; bottom {}'.format(index, face.left(), face.top(), face.right(), face.bottom())) # 在图片中标注人脸,并显示 left = face.left() top = face.top() right = face.right() bottom = face.bottom() cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 3) cv2.namedWindow(f, cv2.WINDOW_AUTOSIZE) cv2.imshow(f, img) # 等待按键,随后退出,销毁窗口 k = cv2.waitKey(0) cv2.destroyAllWindows()官方示例 #!/usr/bin/python # The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt # # This example program shows how to find frontal human faces in an image. In # particular, it shows how you can take a list of images from the command # line and display each on the screen with red boxes overlaid on each human # face. # # The examples/faces folder contains some jpg images of people. You can run # this program on them and see the detections by executing the # following command: # ./face_detector.py ../examples/faces/*.jpg # # This face detector is made using the now classic Histogram of Oriented # Gradients (HOG) feature combined with a linear classifier, an image # pyramid, and sliding window detection scheme. This type of object detector # is fairly general and capable of detecting many types of semi-rigid objects # in addition to human faces. Therefore, if you are interested in making # your own object detectors then read the train_object_detector.py example # program. # # # COMPILING/INSTALLING THE DLIB PYTHON INTERFACE # You can install dlib using the command: # pip install dlib # # Alternatively, if you want to compile dlib yourself then go into the dlib # root folder and run: # python setup.py install # or # python setup.py install --yes USE_AVX_INSTRUCTIONS # if you have a CPU that supports AVX instructions, since this makes some # things run faster. # # Compiling dlib should work on any operating system so long as you have # CMake and boost-python installed. On Ubuntu, this can be done easily by # running the command: # sudo apt-get install libboost-python-dev cmake # # Also note that this example requires scikit-image which can be installed # via the command: # pip install scikit-image # Or downloaded from http://scikit-image.org/download.html. import sys import dlib from skimage import io detector = dlib.get_frontal_face_detector() win = dlib.image_window() for f in sys.argv[1:]: print("Processing file: {}".format(f)) img = io.imread(f) # The 1 in the second argument indicates that we should upsample the image # 1 time. This will make everything bigger and allow us to detect more # faces. dets = detector(img, 1) print("Number of faces detected: {}".format(len(dets))) for i, d in enumerate(dets): print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format( i, d.left(), d.top(), d.right(), d.bottom())) win.clear_overlay() win.set_image(img) win.add_overlay(dets) dlib.hit_enter_to_continue() # Finally, if you really want to you can ask the detector to tell you the score # for each detection. The score is bigger for more confident detections. # The third argument to run is an optional adjustment to the detection threshold, # where a negative value will return more detections and a positive value fewer. # Also, the idx tells you which of the face sub-detectors matched. This can be # used to broadly identify faces in different orientations. if (len(sys.argv[1:]) > 0): img = io.imread(sys.argv[1]) dets, scores, idx = detector.run(img, 1, -1) for i, d in enumerate(dets): print("Detection {}, score: {}, face_type:{}".format( d, scores[i], idx[i]))
2022年07月13日
107 阅读
0 评论
36 点赞
1
2
0:00