C++代码

#include <pybind11/pybind11.h>
#include<opencv2/opencv.hpp>
#include<pybind11/numpy.h>using namespace std;
using namespace cv;
namespace py = pybind11;void BilinearInsert(Mat& src, Mat& dst, float ux, float uy, int i, int j)
{auto Abs = [&](float f) {return f > 0 ? f : -f;};int height = src.rows-1;int width = src.cols-1;int c = src.channels();if (c == 3){//存储图像得浮点坐标CvPoint2D32f uv;CvPoint3D32f f1;CvPoint3D32f f2;//取整数int iu = (int)ux;int iv = (int)uy;if (iu > width){iu = width;}if (iv > height){iv = height;}uv.x = iu + 1;uv.y = iv + 1;//step图象像素行的实际宽度  三个通道进行计算(0 , 1 2  三通道)/*cout << "src.data" << src.data << std::endl;//C++ unsigned char *是表示无符号字符指针的意思//unsigned若省略后一个关键字,大多数编译器都会认为是unsigned int。/*cout << "src.data.type" << typeid(src.data).name() << std::endl;*/f1.x = ((uchar*)(src.data + src.step * iv))[iu * 3] * (1 - Abs(uv.x - iu)) + \((uchar*)(src.data + src.step * iv))[(iu + 1) * 3] * (uv.x - iu);f1.y = ((uchar*)(src.data + src.step * iv))[iu * 3 + 1] * (1 - Abs(uv.x - iu)) + \((uchar*)(src.data + src.step * iv))[(iu + 1) * 3 + 1] * (uv.x - iu);f1.z = ((uchar*)(src.data + src.step * iv))[iu * 3 + 2] * (1 - Abs(uv.x - iu)) + \((uchar*)(src.data + src.step * iv))[(iu + 1) * 3 + 2] * (uv.x - iu);f2.x = ((uchar*)(src.data + src.step * (iv + 1)))[iu * 3] * (1 - Abs(uv.x - iu)) + \/*cout << "f1.x" << f1.x << std::endl;*/((uchar*)(src.data + src.step * (iv + 1)))[(iu + 1) * 3] * (uv.x - iu);f2.y = ((uchar*)(src.data + src.step * (iv + 1)))[iu * 3 + 1] * (1 - Abs(uv.x - iu)) + \((uchar*)(src.data + src.step * (iv + 1)))[(iu + 1) * 3 + 1] * (uv.x - iu);f2.z = ((uchar*)(src.data + src.step * (iv + 1)))[iu * 3 + 2] * (1 - Abs(uv.x - iu)) + \((uchar*)(src.data + src.step * (iv + 1)))[(iu + 1) * 3 + 2] * (uv.x - iu);//step指的字节数,一个图像是3通道,每个通道是16位,那么//其elemsize就是3* (16 / 8) = 6,即每个元素占6个字节((uchar*)(dst.data + dst.step * j))[i * 3] = f1.x * (1 - Abs(uv.y - iv)) + f2.x * (Abs(uv.y - iv));  //三个通道进行赋值((uchar*)(dst.data + dst.step * j))[i * 3 + 1] = f1.y * (1 - Abs(uv.y - iv)) + f2.y * (Abs(uv.y - iv));((uchar*)(dst.data + dst.step * j))[i * 3 + 2] = f1.z * (1 - Abs(uv.y - iv)) + f2.z * (Abs(uv.y - iv));}
}
Mat LocalTranslationWarp_Face(Mat& img, int warpX, int warpY, int endX, int endY, float radius)
{Mat dst = img.clone();//平移距离 float ddradius = radius * radius;//计算|m-c|^2size_t mc = (endX - warpX) * (endX - warpX) + (endY - warpY) * (endY - warpY);//计算 图像的高  宽 通道数量int height = img.rows;int width = img.cols;int chan = img.channels();auto Abs = [&](float f) {return f > 0 ? f : -f;};for (int i = 0; i < width; i++){for (int j = 0; j < height; j++){// # 计算该点是否在形变圆的范围之内//# 优化,第一步,直接判断是会在(startX, startY)的矩阵框中if ((Abs(i - warpX) > radius) && (Abs(j - warpY) > radius))continue;float distance = (i - warpX) * (i - warpX) + (j - warpY) * (j - warpY);if (distance < ddradius){//# 计算出(i, j)坐标的原坐标//# 计算公式中右边平方号里的部分float ratio = (ddradius - distance) / (ddradius - distance + mc);ratio *= ratio;//映射原位置float UX = i - ratio * (endX - warpX);float UY = j - ratio * (endY - warpY);//根据双线性插值得到UX UY的值BilinearInsert(img, dst, UX, UY, i, j);//改变当前的值}}}return dst;}
Mat LocalTranslationWarp_Eye(Mat& img, int warpX, int warpY, int endX, int endY, float radius)
{//平移距离 Mat dst = img.clone();float ddradius = radius * radius;//计算|m-c|^2size_t mc = (endX - warpX) * (endX - warpX) + (endY - warpY) * (endY - warpY);//计算 图像的高  宽 通道数量int height = img.rows;int width = img.cols;int chan = img.channels();auto Abs = [&](float f) {return f > 0 ? f : -f;};for (int i = 0; i < width; i++){for (int j = 0; j < height; j++){// # 计算该点是否在形变圆的范围之内//# 优化,第一步,直接判断是会在(startX, startY)的矩阵框中if ((Abs(i - warpX) > radius) && (Abs(j - warpY) > radius))continue;float distance = (i - warpX) * (i - warpX) + (j - warpY) * (j - warpY);if (distance < ddradius){float rnorm = sqrt(distance) / radius;float ratio = 1 - (rnorm - 1) * (rnorm - 1) * 0.5;//映射原位置float UX = warpX + ratio * (i - warpX);float UY = warpY + ratio * (j - warpY);//根据双线性插值得到UX UY的值BilinearInsert(img, dst, UX, UY, i, j);}}}return dst;}
Mat numpy_uint8_3c_to_cv_mat(py::array_t<unsigned char>& input) {if (input.ndim() != 3)throw std::runtime_error("1-channel image must be 2 dims ");py::buffer_info buf = input.request();Mat mat(buf.shape[0], buf.shape[1], CV_8UC3, (unsigned char*)buf.ptr);//imshow("显示读取图片", mat);return mat;
}
Mat numpy_uint8_1c_to_cv_mat(py::array_t<unsigned char>& input) {if (input.ndim() != 2)throw std::runtime_error("1-channel image must be 2 dims ");py::buffer_info buf = input.request();Mat mat(buf.shape[0], buf.shape[1], CV_8UC1, (unsigned char*)buf.ptr);return mat;
}
py::array_t<unsigned char> cv_mat_uint8_1c_to_numpy(cv::Mat& input) {py::array_t<unsigned char> dst = py::array_t<unsigned char>({ input.rows,input.cols }, input.data);return dst;
}py::array_t<unsigned char> cv_mat_uint8_3c_to_numpy(cv::Mat& input) {py::array_t<unsigned char> dst = py::array_t<unsigned char>({ input.rows,input.cols,3 }, input.data);return dst;
}py::array_t<unsigned char> eyebig(py::array_t<unsigned char>& input, int warpX, int warpY, int endX, int endY, float radius) {Mat img_rgb = numpy_uint8_3c_to_cv_mat(input);//cout << "input.rows" << img_rgb.rows << "input.cols" << img_rgb.cols << endl;Mat dst = LocalTranslationWarp_Eye(img_rgb, warpX, warpY, endX, endY, radius);//imshow("显示读取图片2", dst);return cv_mat_uint8_3c_to_numpy(dst);
}
py::array_t<unsigned char> facethin(py::array_t<unsigned char>& input, int warpX, int warpY, int endX, int endY, float radius) {Mat img_rgb = numpy_uint8_3c_to_cv_mat(input);//cout << "input.rows" << img_rgb.rows << "input.cols" << img_rgb.cols << endl;Mat dst = LocalTranslationWarp_Face(img_rgb, warpX, warpY, endX, endY, radius);//imshow("显示读取图片2", dst);return cv_mat_uint8_3c_to_numpy(dst);
}
py::array_t<unsigned char> test_rgb_to_gray(py::array_t<unsigned char>& input) {Mat img_rgb = numpy_uint8_3c_to_cv_mat(input);Mat dst;cv::cvtColor(img_rgb, dst, cv::COLOR_RGB2GRAY);return cv_mat_uint8_1c_to_numpy(dst);
}PYBIND11_MODULE(py2cpp, m) {m.doc() = "pybind11 example";m.def("LocalTranslationWarp_Eye", &LocalTranslationWarp_Eye, "LocalTranslationWarp_Eye");m.def("test_rgb_to_gray", &test_rgb_to_gray,"test_rgb_to_grayt");m.def("eyebig", &eyebig, "eyebig");m.def("facethin", &facethin, "facethin");}

python代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import py2cpp as obj
import dlib
import cv2
import numpy as np
import math
import time
predictor_path = 'shape_predictor_68_face_landmarks.dat'# 使用dlib自带的frontal_face_detector作为我们的特征提取器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)def landmark_dec_dlib_fun(img_src):#转灰度图img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)#cv2.imshow('grayimg',img_gray)land_marks = []rects = detector(img_gray, 0)print(rects)for i in range(len(rects)):land_marks_node = np.matrix([[p.x, p.y] for p in predictor(img_gray, rects[i]).parts()])# for idx,point in enumerate(land_marks_node):#     # 68点坐标#     pos = (point[0,0],point[0,1])#     print(idx,pos)#     # 利用cv2.circle给每个特征点画一个圈,共68个#     cv2.circle(img_src, pos, 5, color=(0, 255, 0))#     # 利用cv2.putText输出1-68#     font = cv2.FONT_HERSHEY_SIMPLEX#     cv2.putText(img_src, str(idx + 1), pos, font, 0.5, (0, 0, 0), 1, cv2.LINE_AA)land_marks.append(land_marks_node)return land_marks'''
方法1: Interactive Image Warping 局部放大算法
'''
def localTranslationWarp1(srcImg, startX, startY, endX, endY, radius):ddradius = float(radius * radius)copyImg = np.zeros(srcImg.shape, np.uint8)copyImg = srcImg.copy()t1 = time.time()# 计算公式中的|m-c|^2ddmc = (endX - startX) * (endX - startX) + (endY - startY) * (endY - startY)H, W, C = srcImg.shapefor i in range(W):for j in range(H):# 计算该点是否在形变圆的范围之内# 优化,第一步,直接判断是会在(startX,startY)的矩阵框中if math.fabs(i - startX) > radius and math.fabs(j - startY) > radius:continuedistance = (i - startX) * (i - startX) + (j - startY) * (j - startY)if (distance < ddradius):# 计算出(i,j)坐标的原坐标# 计算公式中右边平方号里的部分# ratio = (ddradius - distance) / (ddradius - distance + ddmc)# ratio = ratio * ratiornorm = math.sqrt(distance) / radiusratio = 1 - (rnorm - 1)*(rnorm - 1)*0.5# 映射原位置UX = startX + ratio * (i - startX)UY = startY + ratio * (j - startY)# 根据双线性插值法得到UX,UY的值value = BilinearInsert(srcImg, UX, UY)# 改变当前 i ,j的值copyImg[j, i] = valuereturn copyImg
'''
方法2: Interactive Image Warping 局部平移算法
'''
def localTranslationWarp2(srcImg, startX, startY, endX, endY, radius):ddradius = float(radius * radius)copyImg = np.zeros(srcImg.shape, np.uint8)copyImg = srcImg.copy()# 计算公式中的|m-c|^2ddmc = (endX - startX) * (endX - startX) + (endY - startY) * (endY - startY)H, W, C = srcImg.shapefor i in range(W):for j in range(H):# 计算该点是否在形变圆的范围之内# 优化,第一步,直接判断是会在(startX,startY)的矩阵框中if math.fabs(i - startX) > radius and math.fabs(j - startY) > radius:continuedistance = (i - startX) * (i - startX) + (j - startY) * (j - startY)if (distance < ddradius):# 计算出(i,j)坐标的原坐标# 计算公式中右边平方号里的部分ratio = (ddradius - distance) / (ddradius - distance + ddmc)ratio = ratio * ratio# 映射原位置UX = i - ratio * (endX - startX)UY = j - ratio * (endY - startY)# 根据双线性插值法得到UX,UY的值value = BilinearInsert(srcImg, UX, UY)# 改变当前 i ,j的值copyImg[j, i] = valuereturn copyImgpredictor_path = 'shape_predictor_68_face_landmarks.dat'# 使用dlib自带的frontal_face_detector作为我们的特征提取器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)def landmark_dec_dlib_fun(img_src):#转灰度图img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)#cv2.imshow('grayimg',img_gray)land_marks = []rects = detector(img_gray, 0)#print(rects)for i in range(len(rects)):land_marks_node = np.matrix([[p.x, p.y] for p in predictor(img_gray, rects[i]).parts()])# for idx,point in enumerate(land_marks_node):#     # 68点坐标#     pos = (point[0,0],point[0,1])#     print(idx,pos)#     # 利用cv2.circle给每个特征点画一个圈,共68个#     cv2.circle(img_src, pos, 5, color=(0, 255, 0))#     # 利用cv2.putText输出1-68#     font = cv2.FONT_HERSHEY_SIMPLEX#     cv2.putText(img_src, str(idx + 1), pos, font, 0.5, (0, 0, 0), 1, cv2.LINE_AA)land_marks.append(land_marks_node)return land_marks# 双线性插值法
def BilinearInsert(src, ux, uy):w, h, c = src.shapeif c == 3:x1 = int(ux)x2 = x1 + 1y1 = int(uy)y2 = y1 + 1part1 = src[y1, x1].astype(np.float64) * (float(x2) - ux) * (float(y2) - uy)part2 = src[y1, x2].astype(np.float64) * (ux - float(x1)) * (float(y2) - uy)part3 = src[y2, x1].astype(np.float64) * (float(x2) - ux) * (uy - float(y1))part4 = src[y2, x2].astype(np.float64) * (ux - float(x1)) * (uy - float(y1))insertValue = part1 + part2 + part3 + part4return insertValue.astype(np.int8)src = cv2.imread('1.jpg')landmarks = landmark_dec_dlib_fun(src)
# if len(landmarks) == 0:
#     returnfor landmarks_node in landmarks:# 第4个点左left_landmark = landmarks_node[37]# 第6个点左left_landmark_down = landmarks_node[27]# 第14个点右right_landmark = landmarks_node[44]# 第16个点右right_landmark_down = landmarks_node[27]# 第31个点鼻尖endPt = landmarks_node[30]
def face_big_auto(x):#68个关键点二维数组#landmarks = landmark_dec_dlib_fun(src)if len(landmarks) == 0:returnw = cv2.getTrackbarPos('Bigeye', 'How big the eyes do you want')# 计算第4个点到第6个点的距离作为瘦脸距离# r_left = math.sqrt(#     (left_landmark[0, 0] - left_landmark_down[0, 0]) * (left_landmark[0, 0] - left_landmark_down[0, 0]) +#     (left_landmark[0, 1] - left_landmark_down[0, 1]) * (left_landmark[0, 1] - left_landmark_down[0, 1]))## # 计算第14个点到第16个点的距离作为瘦脸距离# r_right = math.sqrt(#     (right_landmark[0, 0] - right_landmark_down[0, 0]) * (right_landmark[0, 0] - right_landmark_down[0, 0]) +#     (right_landmark[0, 1] - right_landmark_down[0, 1]) * (right_landmark[0, 1] - right_landmark_down[0, 1]))r_left = wr_right = w# 大左边眼# big_image = localTranslationWarp1(src, left_landmark[0, 0], left_landmark[0, 1], endPt[0, 0], endPt[0, 1],#                                   r_left)big_image = obj.eyebig(src, left_landmark[0, 0], left_landmark[0, 1], endPt[0, 0], endPt[0, 1],r_left)# 大右边眼# big_image = localTranslationWarp1(big_image, right_landmark[0, 0], right_landmark[0, 1], endPt[0, 0],#                                   endPt[0, 1], r_right)big_image = obj.eyebig(big_image, right_landmark[0, 0], right_landmark[0, 1], endPt[0, 0],endPt[0, 1], r_right)# 显示cv2.imshow('How big the eyes do you want', big_image)cv2.waitKey(1)def face_thin_auto(x):s = cv2.getTrackbarPos('Thinface', 'How big the eyes do you want')# 如果未检测到人脸关键点,就不进行瘦脸if len(landmarks) == 0:returnfor landmarks_node in landmarks:#第4个点左left_landmark = landmarks_node[3]#第6个点左left_landmark_down = landmarks_node[5]#第14个点右right_landmark = landmarks_node[13]#第16个点右right_landmark_down = landmarks_node[15]#第31个点鼻尖endPt = landmarks_node[30]# 计算第4个点到第6个点的距离作为瘦脸距离# r_left = math.sqrt(#     (left_landmark[0, 0] - left_landmark_down[0, 0]) * (left_landmark[0, 0] - left_landmark_down[0, 0]) +#     (left_landmark[0, 1] - left_landmark_down[0, 1]) * (left_landmark[0, 1] - left_landmark_down[0, 1]))## # 计算第14个点到第16个点的距离作为瘦脸距离# r_right = math.sqrt(#     (right_landmark[0, 0] - right_landmark_down[0, 0]) * (right_landmark[0, 0] - right_landmark_down[0, 0]) +#     (right_landmark[0, 1] - right_landmark_down[0, 1]) * (right_landmark[0, 1] - right_landmark_down[0, 1]))r_left = sr_right = s# 瘦左边脸# thin_image = localTranslationWarp2(src, left_landmark[0, 0], left_landmark[0, 1], endPt[0, 0], endPt[0, 1],#                                   r_left)thin_image = obj.facethin(src, left_landmark[0, 0], left_landmark[0, 1], endPt[0, 0], endPt[0, 1],r_left)# 瘦右边脸# thin_image = localTranslationWarp2(thin_image, right_landmark[0, 0], right_landmark[0, 1], endPt[0, 0],#                                   endPt[0, 1], r_right)thin_image = obj.facethin(thin_image, right_landmark[0, 0], right_landmark[0, 1], endPt[0, 0],endPt[0, 1], r_right)# 显示cv2.imshow('How big the eyes do you want', thin_image)cv2.waitKey(1)cv2.namedWindow('How big the eyes do you want')
cv2.createTrackbar('Bigeye', 'How big the eyes do you want', 0, 70, face_big_auto)
cv2.createTrackbar('Thinface', 'How big the eyes do you want', 0, 60, face_thin_auto)
cv2.imshow('How big the eyes do you want',src)
cv2.waitKey(0)
# while True:
#     #cv2.imshow('How big the eyes do you want', window)
#     ch = cv2.waitKey(1) & 0xFF
#     if ch == 27:
#         breakcv2.destroyAllWindows()

pybind11用python调用C++代码相关推荐

  1. Python调用Java代码部署及初步使用

    Python调用Java代码部署: jpype下载地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#jpype 下载的时候需要使用Chrome浏览器进行下载 ...

  2. python调用java代码方法

    前言: 公司要测试对外接口,接口中的数据又涉及到加密的问题,而python对加密数据进行位运算后,居然无法逆向位运算回来了(应该是个人能力不够吧),只好调用同事之前用的java代码中的函数去解码了,花 ...

  3. 如何实现Python调用C代码--python与C之间如何通信(swig)

    转载: https://www.zhihu.com/question/23003213 1. C代码如何调用Python 1.1 test #include <Python.h> int ...

  4. python调用opencv代码_Python调用OpenCV实现图像平滑代码实例

    主要讲解Python调用OpenCV实现图像平滑,包括四个算法:均值滤波.方框滤波.高斯滤波和中值滤波. 给图像增加噪声: import cv2 import numpy as np def test ...

  5. python调用c代码

    Linux环境下使用python调用C的printf例子: #!/usr/bin/env python2.7 #-*- coding:utf-8 -*- from ctypes import * de ...

  6. PyO3: python调用rust代码尝试

    PyO3功能很强大,是python和rust之间交互桥梁.今天主要试验一下python端调用rust端编译的代码库. 说明:本文环境中在windos平台和WSL下 unbuntu18.04平台.lin ...

  7. 二十四节气查询 Python调用示例代码

    二十四节气的时间.由来.习俗以及养生 二十四节气查询 查询二十四节气 复制代码 查询节气详情 复制代码 注意,该示例代码仅适用于 www.apishop.net网站下API 使用该产品前,您需要通过 ...

  8. python操作js中的输入_Python调用JavaScript代码的方法

    准备阶段: 以一段简单的JS脚本为例,将代码写入到文件中,其中,定义了一个方法,计算两个数的和. //norm.js //计算两个数的和 function add(num1, num2) { retu ...

  9. 如何让python调用C和C++代码

    如何让python调用C和C++代码   作者:tamsyn  来源:www.sqlite.com.cn  时间:2008-1-10  [ 字体:大 中 小 ] [ 双击滚屏 ]       安装py ...

  10. 从Python调用C / C ++?

    构造与C或C ++库的Python绑定的最快方法是什么? (如果这很重要,我正在使用Windows.) #1楼 最快的方法是使用SWIG . 来自SWIG 教程的示例 : /* File : exam ...

最新文章

  1. 360极速浏览器崩溃_360极速浏览器12.0新版上线 四大亮点引国内浏览器浪潮
  2. POJ 2823 Sliding Window(单调队列)
  3. 体育直播软件发展的三个阶段
  4. php5.4.45的php.ini文件
  5. 程序员的算法课(11)-KMP算法
  6. 【Flink】FLink assigned slot xx was removed
  7. 如何成为一枝独秀的技术领导者?
  8. 图像处理之局部二值特征
  9. 仔细看看Javascript中的逻辑与()和逻辑或(||)
  10. Mac 效率工具必备神器 —— Alfred
  11. k3 lede刷官改_斐讯 K3 路由 LEDE 固件刷回官方原版固件
  12. 凯恩帝数控系统面板介绍_凯恩帝数控车床操作面板按钮详解
  13. matplotlib论文图片配色
  14. todo已完成任务_我已经完成了自己该做的任务用英文怎么
  15. 微商相册服务器维护,微商相册
  16. usb无线网卡和U盘同时使用
  17. ZigBee 3.0实战教程-Silicon Labs EFR32+EmberZnet-3-01:BootLoader+Application的开发模式
  18. GetKeyState、GetAsyncKeyState、GetKeyboardState函数的区别 以及虚拟键值
  19. word文档及其历史版本的备份
  20. 日语学习资料PDF下载

热门文章

  1. netcore里使用jwt做登陆授权
  2. DUBBO服务启动过程
  3. 《无线网络:理解和应对互联网环境下网络互连所带来的挑战》——2.2 IEEE
  4. IOS快速集成下拉上拉刷新
  5. Java多线程-线程的生命周期
  6. 【总结——HTTP协议】
  7. ASP.NET MVC Framework体验(1):从一个简单实例开始(转)
  8. Windows 8.1安装python出现api-ms-win-crt-runtime-l1-1-0.dll
  9. 对String值不可变的理解以及String类型的引用传递问题
  10. Infopath 2013 通过UserProfileService读取AD用户信息