您好,
会员登录 快速注册
退出 ( 条未读消息)
关于本站 意见反馈 首页

公告:小宅博客网可以开发票了,需要发票的,去群里找群主哈!!
全部文章分类
  • 人工智能 >

  • 编程语言 >

  • WPF系列 >

  • ASP.NET系列 >

  • Linux >

  • 数据库 >

  • 嵌入式 >

  • WEB技术 >

  • PLC系列 >

  • 微服务与框架 >

  • 小宅DIY >

  • 学习资料 >

OpenCv基础 ANN车牌识别 yolov5车牌识别 指针式仪表识别 ROS系列 YOLO Halcon Detectron2 昇腾AI ChatGPT在线体验 英伟达JETSON ChatGLM ChatTTS FunASR 地平线 ByteTrack 魔搭社区 LangChain
C C# C++ Python Java Go
WPF
ASP.NET小功能 GPS定位系统-MVC GPS定位系统-VUE ASP.NET WebRTC
Linux Linux内核 Shell MakeFile
MySql SqlServer Oracle
STM8 STM32 51单片机
VUE入门 HTML JavaScript CSS layui镜像网站 ElementUi中文官网 element-plus 图标
三菱 欧姆龙 西门子 施耐德 松下 台达
IOTSharp IOTGateway ABP FRAMEWORK Docker
亚克力音响 编程仙途:智驭万法
面试题与技巧 Python入门技能树 微软C#教程
首页 编程之美 工具下载 全国就业 流量地图 文心一言
OpenCv基础
内容介绍与资料分享 C# OpenCv环境搭建 C++ OpenCv环境搭建 Python OpenCv环境搭建 Java OpenCv环境搭建 OpenCv组件结构解析 OpenCv命名规范 OpenCv基本专业术语与方法 OpenCV 常用函数与构造体详细说明 创建画布 打开一张图片 利用imwrite生成透明png图像 图像打开、混合显示和输出 图像腐蚀 blur图像模糊(均值滤波) sobel边缘检测 canny边缘检测 Scharr滤波器 程序性能检测及优化 视频播放 摄像头录像与播放 双摄像头操作与图像相似度检测 颜色空间转换与物体追踪 彩色目标追踪 光流法运动目标检测 OpenCV中的稠密光流 背景减除 点追踪 人脸识别 支持向量机之SVM引导 支持向量机之处理线性不可分数据 ROI矩形截取 鼠标绘制矩形 用OpenCV进行基本绘图 绘图函数(python中文显示) 把鼠标当画笔 用滑动条做调色板 图像的基础操作 图像上的算术运算 多通道图像混合 图像的亮度、对比度调整 XML和YAML文件的写入 XML和YAML文件的读取 卷积操作 三种线性滤波 两种非线性滤波 7种图像处理形态学(1) 7种图像处理形态学(2) 漫水填充 图像缩放与图像金字塔 二值化基本阈值操作 图像阈值 Laplacian图像变换(拉普拉斯算子) 霍夫变换HoughLines边缘检测与线性矢量 霍夫变换HoughLinesP边缘检测与线性矢量 霍夫变换HoughCircles边缘检测与线性矢量 LSD快速直线检测 几何变换 remap重映射 remap实现多种重映射 仿射变换综合示例 直方图均衡化 CLAHE有限对比适应性直方图均衡化 draw最大的轮廓 轮廓的性质 点到多边形的最短距离 形状匹配 椭圆拟合与直线拟合 基础轮廓查找 查找并绘制轮廓综合示例 凸缺陷/凸包检测 凸包检测 创建包围轮廓的矩形边界 创建包围轮廓的圆形边 创建包围轮廓的矩形和圆形边界框 查找和绘制图片轮廓矩 分水岭算法 图像修补 H-S二维直方图的绘制/2D直方图 一维直方图的绘制 RGB三色直方图的绘制 直方图对比 使用掩膜绘制直方图 直方图反向投影 模板匹配 多对象模板匹配 cornerHarris角点检测 cornerHarris角点检测综合示例 Shi-Tomasi角点检测 亚像素级角点检测 角点检测的FAST算法(FAST特征检测器) 颜色识别 warpPerspective透视变换 SURF/SIFT特征点检测 SURF/SIFT特征描述 使用FLANN进行特征点匹配 FLANN结合SURF/SIFT进行关键点的描述和匹配 寻找已知物体(一) 寻找已知物体(二) 目标查找与跟踪 - Meanshift与CamShift BRIEF描述符 ORB ORB算法描述与匹配 LUT 图像灰度调整 离散傅里叶变换 双目摄像头与图像拼接 环境亮度检测 stitching 全景拼接 Maze-Solver迷宫解密 使用Haar分类器之面部检测 使用Haar分类器之行人检测 OpenCv Haar/LBP/HOG分类器-人脸识别 斑点检测 使用GrabCut算法进行交互式前景提取 对极几何 摄像机标定 姿势估计 立体图像中的深度地图 OpenCv中的KNN KNN手写数字识别 ​SVM手写数字识别(使用SVM进行手写数据OCR) 英文字母的OCR 预测手写数字(预测不准) K值聚类(一) K值聚类(二) 计算摄影学-图像去噪 高动态范围成像(HDRI或HDR) MSER区域检测 二维码、条形码识别 删除图像中的水印 OpenCv深度学习dnn Kinect-深度相机 OpenCv常用数学算法 360度旋转直线绘制 向量延长线上的像素扫描 Tools工具包-窗体分配
图像的基础操作
多通道图像混合
激萌の小宅 小宅博客网 OpenCv基础

文章作者:激萌の小宅

促销:¥0

价格:¥0

配送方式: 购买后立即生效(如购买异常,请联系站长)
付款之后一定要等待自动跳转结束,否则购买可能会失败
  • 0 天

    有效期

  • 0

    总销量

  • 0

    累计评价

图像上的算术运算

当前系列所有demo下载地址:

https://github.com/GaoRenBao/OpenCv4-Demo

不同编程语言对应的OpenCv版本以及开发环境信息如下: 

语言

OpenCv版本

IDE

C#

OpenCvSharp4.4.8.0.20230708

Visual Studio 2022

C++

OpenCv-4.5.5-vc14_vc15

Visual Studio 2022

Python

OpenCv-Python (4.6.0.66)

PyCharm Community Edition 2022.1.3


我们测试用的图片如下:

subtract1.jpg

subtract2.jpg


demo1:图像的减法运算

微信截图_20220829211926.jpg


demo2:通过图像相减,查找扑克牌位置

微信截图_20220829212231.jpg


demo3:通过图像相减,凸显扑克牌位置

QQ截图20220829212406.jpg


demo4:调用摄像头,通过图像相减,标记扑克牌位置

6379740599035057869137285 (1).gif


C#版本运行代码如下:

using OpenCvSharp;
using System;

namespace demo
{
    internal class Program
    {

        static void Main(string[] args)
        {
            demo1();
            //demo2();
            //demo3();
            //demo4();
        }

        public static void myImshow(string name, Mat img)
        {
            Mat temp = new Mat();
            Cv2.Resize(img, temp, new Size(img.Cols * 1, img.Rows * 1), 0, 0, InterpolationFlags.Nearest);
            Cv2.ImShow(name, temp);
        }

        #region 图像相减1:图像的减法运算
        public static void demo1()
        {
            Mat img1 = Cv2.ImRead("../../../images/subtract1.jpg", 0); // 灰度图
            Mat img2 = Cv2.ImRead("../../../images/subtract2.jpg", 0);

            myImshow("subtract1", img1);
            myImshow("subtract2", img2);

            Mat st = img2 - img1;
            myImshow("after subtract", st);

            Mat threshold = new Mat();
            Cv2.Threshold(st, threshold, 50, 255, ThresholdTypes.Binary);

            myImshow("after threshold", threshold);
            Cv2.WaitKey(0);
        }
        #endregion

        #region 图像相减2:通过图像相减,查找扑克牌位置
        public static void demo2()
        {
            Mat img1 = Cv2.ImRead("../../../images/subtract1.jpg", 0);
            Mat img22 = Cv2.ImRead("../../../images/subtract2.jpg");

            Mat img2 = new Mat();
            Cv2.CvtColor(img22, img2, ColorConversionCodes.BGR2GRAY);

            Mat st = new Mat();
            Cv2.Subtract(img2, img1, st);
            //Cv2.Subtract(img1, img2, st); // 相反

            // 把小于5的像素点设为0
            for (int i = 0; i < st.Rows; ++i)
            {
                for (int j = 0; j < st.Cols; ++j)
                {
                    byte rgb = st.At<byte>(i, j);
                    if (rgb > 0 && rgb <= 5)
                        st.Set(i, j, 0);
                }
            }

            Mat threshold = new Mat();
            Cv2.Threshold(st, threshold, 50, 255, ThresholdTypes.Binary);

            Point[][] contours = new Point[][] { };
            HierarchyIndex[] hierarcy;
            Cv2.FindContours(threshold, out contours, out hierarcy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple, null);

            //List<(int, double)> areas = new List<(int, double)>();
            //for (int i = 0; i < contours.Length; i++)
            //{
            //    areas.Add((i, Cv2.ContourArea(contours[i])));
            //}
            //// 降序排序
            //var a2 = areas.OrderByDescending(x => x.Item2).ToList();
            //foreach(var are in a2)
            //{
            //    if (are.Item2 < 100)
            //        continue;
            //    Cv2.DrawContours(img22, contours, are.Item1, new Scalar(0, 0, 255), 3);
            //    myImshow("approxPolyDP", img22);
            //    Cv2.WaitKey(0);
            //}

            // TODO 截取原图,把长方形纠正
            Point[] cnt = contours[0];
            Point[] hull = Cv2.ConvexHull(cnt);
            double epsilon = 0.001 * Cv2.ArcLength(hull, true);
            Point[] simplified_cnt = Cv2.ApproxPolyDP(hull, epsilon, true);

            epsilon = 0.1 * Cv2.ArcLength(cnt, true);
            Point[] approx = Cv2.ApproxPolyDP(cnt, epsilon, true);
            Point[][] approxs = new Point[][] { approx };

            Cv2.DrawContours(img22, approxs, 0, new Scalar(255, 0, 0), 3);
            myImshow("approxPolyDP", img22);
            Cv2.WaitKey(0);
        }
        #endregion

        #region 图像相减3:通过图像相减,凸显扑克牌位置
        //  returns just the difference of the two images
        public static Mat diff(Mat img, Mat img1)
        {
            Mat diff = new Mat();
            Cv2.Absdiff(img, img1, diff);
            return diff;
        }

        // removes the background but requires three images
        public static Mat diff_remove_bg(Mat img0, Mat img, Mat img1)
        {
            Mat d1 = diff(img0, img);
            Mat d2 = diff(img, img1);
            Mat a = new Mat();
            Cv2.BitwiseAnd(d1, d2, a);
            return a;
        }

        public static void demo3()
        {
            Mat img1 = Cv2.ImRead("../../../images/subtract1.jpg", 0);
            Mat img2 = Cv2.ImRead("../../../images/subtract2.jpg", 0);
            myImshow("subtract1", img1);
            myImshow("subtract2", img2);
            Mat st = diff_remove_bg(img2, img1, img2);
            myImshow("after subtract", st);
            Cv2.WaitKey(0);
        }
        #endregion

        #region 调用摄像头,通过图像相减,标记扑克牌位置
        public static void demo4()
        {
            VideoCapture Cap = new VideoCapture();
            Cap.Open(0);
            // 判断摄像头是否成功打开
            if (!Cap.IsOpened())
            {
                Console.WriteLine("摄像头打开失败.");
                return;
            }

            /* opencv3 */
            //Cap.Set(CaptureProperty.FrameWidth, 1280);  // 设置采集的图像宽度
            //Cap.Set(CaptureProperty.FrameHeight, 720); // 设置采集的图像高度

            /* opencv4 */
            Cap.Set(VideoCaptureProperties.FrameWidth, 1280);  // 设置采集的图像宽度
            Cap.Set(VideoCaptureProperties.FrameHeight, 720); // 设置采集的图像高度
            //Cap.Set(VideoCaptureProperties.Exposure, 0); // 设置曝光值

            Mat bgimg0 = new Mat();
            Mat bgimg = new Mat();
            int frame_no = 10; // 第10帧稳定图像
            while (frame_no > 0)
            {
                if (Cap.Read(bgimg0))
                    frame_no--;
            }
            Cv2.CvtColor(bgimg0, bgimg, ColorConversionCodes.BGR2GRAY);

            Mat frame = new Mat();
            Mat gray = new Mat();
            Mat st = new Mat();
            Mat img = new Mat();
            while (true)
            {
                if (Cap.Read(frame))
                {
                    Cv2.CvtColor(frame, gray, ColorConversionCodes.BGR2GRAY);
                    Cv2.Subtract(gray, bgimg, st);

                    Mat threshold = new Mat();
                    Cv2.Threshold(st, threshold, 50, 255, ThresholdTypes.Binary);

                    Point[][] contours = new Point[][] { };
                    HierarchyIndex[] hierarcy;
                    Cv2.FindContours(threshold, out contours, out hierarcy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple, null);

                    Cv2.DrawContours(st, contours, -1, new Scalar(255, 255, 255), 3);
                    img = st;

                    for (int i = 0; i < contours.Length; i++)
                    {
                        var area = Cv2.ContourArea(contours[i]);
                        if (area < 200)
                            continue;

                        double peri = Cv2.ArcLength(contours[i], true);
                        Point[] approx = Cv2.ApproxPolyDP(contours[i], 0.04 * peri, true);
                        if (approx.Length == 4)
                        {
                            Rect rect = Cv2.BoundingRect(approx);
                            Cv2.Rectangle(frame, new Point(rect.X, rect.Y),
                                new Point(rect.X + rect.Width, rect.Y + rect.Height),
                                new Scalar(0, 0, 255), 2);
                        }
                    }

                    // TODO 对比前几/十几帧,新放一张扑克,知道是那张
                    // 等待图像稳定,不放牌后,再计算
                    myImshow("frame", frame);
                    myImshow("subtract", img);
                    myImshow("threshold", threshold);

                    Cv2.WaitKey(1);
                }
            }
        }
        #endregion
    }
}


C++版本运行代码如下:

#include <opencv2/opencv.hpp>
#include <opencv2/cvconfig.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>    

#include <io.h>
#include <string>
#include <iostream>

using namespace cv;
using namespace std;

void myImshow(string name, Mat img)
{
    Mat temp;
    cv::resize(img, temp, Size(img.cols * 1, img.rows * 1), 0, 0, 3);
    cv::imshow(name, temp);
}

// 图像相减1:图像的减法运算
void demo1()
{
    Mat img1 = cv::imread("../images/subtract1.jpg", 0); // 灰度图
    Mat img2 = cv::imread("../images/subtract2.jpg", 0); // 灰度图

    myImshow("subtract1", img1);
    myImshow("subtract2", img2);

    Mat st = img2 - img1;
    myImshow("after subtract", st);

    Mat threshold;
    cv::threshold(st, threshold, 50, 255, THRESH_BINARY);

    myImshow("after threshold", threshold);
    cv::waitKey(0);
}

// 图像相减2:通过图像相减,查找扑克牌位置
void demo2()
{
    Mat img1 = cv::imread("../images/subtract1.jpg", 0);
    Mat img22 = cv::imread("../images/subtract2.jpg");

    Mat img2;
    cv::cvtColor(img22, img2, COLOR_BGR2GRAY);

    Mat st;
    cv::subtract(img2, img1, st);
    //cv::Subtract(img1, img2, st); // 相反

    // 把小于5的像素点设为0
    for (int i = 0; i < st.rows; ++i)
    {
        for (int j = 0; j < st.cols; ++j)
        {
            char rgb = st.at<char>(i, j);
            if (rgb > 0 && rgb <= 5)
                st.at<char>(i, j) = 0;
        }
    }

    Mat threshold;
    cv::threshold(st, threshold, 50, 255, THRESH_BINARY);

    vector<vector<Point>> contours;
    vector<Vec4i> hierarcy;
    findContours(threshold, contours, hierarcy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));

    //for (int i = 0; i < contours.size(); i++)
    //{
    //    int area = cv::contourArea(contours[i]);
    //    if (area < 100)
    //        continue;

    //    cv::drawContours(img22, contours, i, Scalar(0, 0, 255), 3);
    //    myImshow("approxPolyDP", img22);
    //    cv::waitKey(0);
    //}

    // TODO 截取原图,把长方形纠正
    vector<Point> cnt = contours[0];
    vector<Point> hull;
    cv::convexHull(cnt, hull);
    double epsilon = 0.001 * cv::arcLength(hull, true);
    std::vector<cv::Point> simplified_cnt;
    cv::approxPolyDP(hull, simplified_cnt, epsilon, true);

    epsilon = 0.1 * cv::arcLength(cnt, true);
    vector<Point> approx;
    cv::approxPolyDP(cnt, approx, epsilon, true);
    vector<vector<Point>> approxs;
    approxs.push_back(approx);

    cv::drawContours(img22, approxs, 0, Scalar(255, 0, 0), 3);
    myImshow("approxPolyDP", img22);
    cv::waitKey(0);
}

//  returns just the difference of the two images
Mat diff(Mat img, Mat img1)
{
    Mat diff;
    cv::absdiff(img, img1, diff);
    return diff;
}
// removes the background but requires three images
Mat diff_remove_bg(Mat img0, Mat img, Mat img1)
{
    Mat d1 = diff(img0, img);
    Mat d2 = diff(img, img1);
    Mat a;
    cv::bitwise_and(d1, d2, a);
    return a;
}
// 图像相减3:通过图像相减,凸显扑克牌位置
void demo3()
{
    Mat img1 = cv::imread("../images/subtract1.jpg", 0);
    Mat img2 = cv::imread("../images/subtract2.jpg", 0);
    myImshow("subtract1", img1);
    myImshow("subtract2", img2);
    Mat st = diff_remove_bg(img2, img1, img2);
    myImshow("after subtract", st);
    cv::waitKey(0);
}

// 调用摄像头,通过图像相减,标记扑克牌位置
void demo4()
{
    VideoCapture cap;
    cap.open(0);
    if (!cap.isOpened())
    {
        cout << "摄像头打开失败." << endl;
        while (true);
        return;
    }

    //cap.set(CAP_PROP_FRAME_WIDTH, 1280);  // 宽度
    //cap.set(CAP_PROP_FRAME_HEIGHT, 720); // 高度
    //cap.set(CAP_PROP_EXPOSURE, 0);     // 曝光

    Mat bgimg0;
    Mat bgimg;
    int frame_no = 10; // 第10帧稳定图像
    while (frame_no > 0)
    {
        cap >> bgimg0;
        if (!bgimg0.empty())
        {
            frame_no--;
        }
    }
    cv::cvtColor(bgimg0, bgimg, COLOR_BGR2GRAY);

    Mat frame;
    Mat gray;
    Mat st;
    Mat img;
    while (true)
    {
        cap >> frame;
        if (!frame.empty())
        {
            cv::cvtColor(frame, gray, COLOR_BGR2GRAY);
            cv::subtract(gray, bgimg, st);

            Mat threshold;
            cv::threshold(st, threshold, 50, 255, THRESH_BINARY);

            vector<vector<Point>> contours;
            vector<Vec4i> hierarcy;
            findContours(threshold, contours, hierarcy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
            cv::drawContours(st, contours, -1, Scalar(255, 255, 255), 3);
            img = st;

            for (int i = 0; i < contours.size(); i++)
            {
                int area = cv::contourArea(contours[i]);
                if (area < 200)
                    continue;

                double peri = cv::arcLength(contours[i], true);
                vector<Point> approx;
                cv::approxPolyDP(contours[i], approx, 0.04 * peri, true);
                if (approx.size() == 4)
                {
                    Rect rect = cv::boundingRect(approx);
                    cv::rectangle(frame, Point(rect.x, rect.y),
                        Point(rect.x + rect.width, rect.y + rect.height),
                        Scalar(0, 0, 255), 2);
                }
            }

            // TODO 对比前几/十几帧,新放一张扑克,知道是那张
            // 等待图像稳定,不放牌后,再计算
            myImshow("frame", frame);
            myImshow("subtract", img);
            myImshow("threshold", threshold);

            cv::waitKey(1);
        }
    }
}

int main()
{
    demo1();
    //demo2();
    //demo3();
    //demo4();
}


Python版本运行效果及代码如下:

demo1.py:图像的减法运算:

import cv2

# img1=cv2.imread('../images/subtract1.jpg')
img1 = cv2.imread('../images/subtract1.jpg', 0)  # 灰度图
# img2=cv2.imread('../images/subtract2.jpg')
img2 = cv2.imread('../images/subtract2.jpg', 0)

cv2.imshow('subtract1', img1)
cv2.imshow('subtract2', img2)

#
st = img2 - img1
# st=img1-img2#相反
cv2.imshow('after subtract', st)

# 效果好一点
# ret,threshold=cv2.threshold(st,0, 127, cv2.THRESH_BINARY)
ret, threshold = cv2.threshold(st, 50, 255, cv2.THRESH_BINARY)
cv2.imshow('after threshold', threshold)

cv2.waitKey(0)


demo2.py:通过图像相减,查找扑克牌位置:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# img1=cv2.imread('../images/subtract1.jpg')
img1 = cv2.imread('../images/subtract1.jpg', 0)  # 灰度图
# img2=cv2.imread('../images/subtract2.jpg')
# img2 = cv2.imread('../images/subtract2.jpg', 0)
img22 = cv2.imread('../images/subtract2.jpg')
img2 = cv2.cvtColor(img22, cv2.COLOR_BGR2GRAY)

# cv2.imshow('subtract1', img1)
# cv2.imshow('subtract2', img2)

#
st = cv2.subtract(img2, img1)
# st = cv2.subtract(img1, img2)#相反
st[st <= 5] = 0  # 把小于20的像素点设为0

# cv2.imshow('after subtract', st)

'''
# 直方图,看看大部分像素集中在哪个区域
# plt.plot(st)
pxs = st.ravel()
pxs=[x for x in pxs if x>5]#20,10
plt.hist(pxs, 256, [0, 256])
plt.show()
'''

# 效果好一点
# ret,threshold=cv2.threshold(st,0, 127, cv2.THRESH_BINARY)
ret, threshold = cv2.threshold(st, 50, 255, cv2.THRESH_BINARY)
# cv2.imshow('after threshold', threshold)

contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

areas = list()
for i, cnt in enumerate(contours):
    areas.append((i, cv2.contourArea(cnt)))

#
a2 = sorted(areas, key=lambda d: d[1], reverse=True)

'''
for i,are in a2:
    if are <100:
        continue
    cv2.drawContours(img22, contours, i, (0, 0, 255), 3)
    print(i,are)

    cv2.imshow('drawContours',img22)
    cv2.waitKey(0)
# cv2.destroyAllWindows()
'''

# TODO 截取原图,把长方形纠正
cnt = contours[0]
print(cnt)
hull = cv2.convexHull(cnt)
epsilon = 0.001 * cv2.arcLength(hull, True)
simplified_cnt = cv2.approxPolyDP(hull, epsilon, True)

epsilon = 0.1 * cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
print(approx)
cv2.drawContours(img22, [approx], 0, (255, 0, 0), 3)
cv2.imshow('approxPolyDP', img22)
cv2.waitKey(0)
exit(3)

# findHomography(srcPoints, dstPoints, method=None, ransacReprojThreshold=None, mask=None, maxIters=None, confidence=None)
# H = cv2.findHomography(srcPoints=cnt.astype('single'), dstPoints=np.array([[[0., 0.]], [[2150., 0.]], [[2150., 2800.]], [[0., 2800.]]]))
# M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)


# now that we have our screen contour, we need to determine
# the top-left, top-right, bottom-right, and bottom-left
# points so that we can later warp the image -- we'll start
# by reshaping our contour to be our finals and initializing
# our output rectangle in top-left, top-right, bottom-right,
# and bottom-left order
pts = approx.reshape(4, 2)
rect = np.zeros((4, 2), dtype="float32")

# the top-left point has the smallest sum whereas the
# bottom-right has the largest sum
s = pts.sum(axis=1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]

# compute the difference between the points -- the top-right
# will have the minumum difference and the bottom-left will
# have the maximum difference
diff = np.diff(pts, axis=1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]

# multiply the rectangle by the original ratio
ratio = image.shape[0] / 300.0
rect *= ratio

# now that we have our rectangle of points, let's compute
# the width of our new image
(tl, tr, br, bl) = rect
widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))

# ...and now for the height of our new image
heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))

# take the maximum of the width and height values to reach
# our final dimensions
maxWidth = max(int(widthA), int(widthB))
maxHeight = max(int(heightA), int(heightB))

# construct our destination points which will be used to
# map the screen to a top-down, "birds eye" view
dst = np.array([
    [0, 0],
    [maxWidth - 1, 0],
    [maxWidth - 1, maxHeight - 1],
    [0, maxHeight - 1]], dtype="float32")

# calculate the perspective transform matrix and warp
# the perspective to grab the screen
M = cv2.getPerspectiveTransform(rect, dst)
warp = cv2.warpPerspective(img22, M, (maxWidth, maxHeight))

# final_image = cv2.warpPerspective(img22, H, (2150, 2800))

cv2.imshow('final_image', warp)
cv2.waitKey(0)


demo3.py:通过图像相减,凸显扑克牌位置:

"""
图像相减3.py:

3张图片

"""
import cv2

def diff(img, img1):  # returns just the difference of the two images
    return cv2.absdiff(img, img1)


def diff_remove_bg(img0, img, img1):  # removes the background but requires three images
    d1 = diff(img0, img)
    d2 = diff(img, img1)
    return cv2.bitwise_and(d1, d2)


# img1=cv2.imread('subtract1.jpg')
img1 = cv2.imread('subtract1.jpg', 0)  # 灰度图
# img2=cv2.imread('subtract2.jpg')
img2 = cv2.imread('subtract2.jpg', 0)

cv2.imshow('subtract1', img1)
cv2.imshow('subtract2', img2)

st = diff_remove_bg(img2, img1,img2)
cv2.imshow('after subtract', st)

cv2.waitKey(0)


demo4.py:调用摄像头,通过图像相减,标记扑克牌位置:

import cv2
import numpy as np

def myImshow(name,img):
    imgH = img.shape[0]
    imgW = img.shape[1]
    temp = cv2.resize(img, ((int)(imgW*0.5), (int)(imgH*0.5)), interpolation = cv2.INTER_NEAREST)
    cv2.imshow(name, temp)

# 外部摄像头默认好像是CAP_MSMF格式,会导致摄像头无法打开,设置成CAP_DSHOW就可以了
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
#ret = cap.set(3, 640)
#ret = cap.set(4, 480)

ret =  cap.set(cv2.CAP_PROP_FRAME_WIDTH,1280)  # 设置图像宽
ret =  cap.set(cv2.CAP_PROP_FRAME_HEIGHT,720) # 设置图像高
ret =  cap.set(cv2.CAP_PROP_EXPOSURE, 0)     # 设置曝光值

cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
'''
cal=[cap.read()[1] for x in range(20)]

#mean 直接的加减是不行的
# bgimg0=np.mean(np.sum(cal))
# bgimg0=np.average(cal)
# bgimg0=np.mean(cal)
nps1=sum(cal)
mean1=nps1/len(cal)
# mean1[mean1<0]=0
# mean1[mean1>255]=255
cv2.imshow('bgimg', mean1)
cv2.waitKey(0)
exit(3)
'''

frame_no = 100
# cap.set(1, frame_no)#第10帧
ret, bgimg0 = cap.read()  # 背景
bgimg = cv2.cvtColor(bgimg0, cv2.COLOR_BGR2GRAY)
myImshow('bgimg' + str(frame_no), bgimg0)
# cv2.imwrite('desk_bgimg.jpg',bgimg)

while cap.isOpened():
    ret, frame = cap.read()  # TODO 图像稳定
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    #
    st = cv2.subtract(gray, bgimg)
    # st = cv2.subtract(img1, img2)#相反
    # st[st <= 5] = 0  # 把小于20的像素点设为0

    ret, threshold = cv2.threshold(st, 50, 255, cv2.THRESH_BINARY)
    contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    print("contours size: ", len(contours))

    # img = cv2.drawContours(st, contours, -1, (0, 0, 0), 13)
    img = cv2.drawContours(st, contours, -1, (255, 255, 255), 3)
    #
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area < 200:
            continue

        peri = cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, 0.04 * peri, True)
        if len(approx) == 4:
            (x, y, w, h) = cv2.boundingRect(approx)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)

    # TODO 对比前几/十几帧,新放一张扑克,知道是那张
    # 等待图像稳定,不放牌后,再计算

    myImshow("frame", frame)
    myImshow("subtract", img)
    # cv2.moveWindow("subtract", y=bgimg.shape[0], x=0)
    myImshow('threshold', threshold)
    # cv2.moveWindow("threshold", x=bgimg.shape[1], y=0)

    key = cv2.waitKey(delay=1)
    if key == ord("q"):
        break
    elif key == ord("s"):
        cv2.imwrite('poker-threshold.jpg', threshold)

cv2.destroyAllWindows()


图像的基础操作
多通道图像混合

友情链接: CSDN激萌の小宅 95知识库 自考题库 罗分明个人网络博客 精益编程leanboot

小宅博客  www.bilibili996.com All Rights Reserved. 备案号: 闽ICP备2024034575号

网站经营许可证  福建省福州市 Copyright©2021-2025 版权所有

小宅博客
首页 智能家居 地图定位
公告:小宅博客网可以开发票了,需要发票的,去群里找群主哈!!

文章作者:激萌の小宅

促销:¥0

价格:¥0

配送方式: 购买后立即生效(如购买异常,请联系站长)
付款之后一定要等待自动跳转结束,否则购买可能会失败
  • 0 天

    有效期

  • 0

    总销量

  • 0

    累计评价

图像上的算术运算

当前系列所有demo下载地址:

https://github.com/GaoRenBao/OpenCv4-Demo

不同编程语言对应的OpenCv版本以及开发环境信息如下: 

语言

OpenCv版本

IDE

C#

OpenCvSharp4.4.8.0.20230708

Visual Studio 2022

C++

OpenCv-4.5.5-vc14_vc15

Visual Studio 2022

Python

OpenCv-Python (4.6.0.66)

PyCharm Community Edition 2022.1.3


我们测试用的图片如下:

subtract1.jpg

subtract2.jpg


demo1:图像的减法运算

微信截图_20220829211926.jpg


demo2:通过图像相减,查找扑克牌位置

微信截图_20220829212231.jpg


demo3:通过图像相减,凸显扑克牌位置

QQ截图20220829212406.jpg


demo4:调用摄像头,通过图像相减,标记扑克牌位置

6379740599035057869137285 (1).gif


C#版本运行代码如下:

using OpenCvSharp;
using System;

namespace demo
{
    internal class Program
    {

        static void Main(string[] args)
        {
            demo1();
            //demo2();
            //demo3();
            //demo4();
        }

        public static void myImshow(string name, Mat img)
        {
            Mat temp = new Mat();
            Cv2.Resize(img, temp, new Size(img.Cols * 1, img.Rows * 1), 0, 0, InterpolationFlags.Nearest);
            Cv2.ImShow(name, temp);
        }

        #region 图像相减1:图像的减法运算
        public static void demo1()
        {
            Mat img1 = Cv2.ImRead("../../../images/subtract1.jpg", 0); // 灰度图
            Mat img2 = Cv2.ImRead("../../../images/subtract2.jpg", 0);

            myImshow("subtract1", img1);
            myImshow("subtract2", img2);

            Mat st = img2 - img1;
            myImshow("after subtract", st);

            Mat threshold = new Mat();
            Cv2.Threshold(st, threshold, 50, 255, ThresholdTypes.Binary);

            myImshow("after threshold", threshold);
            Cv2.WaitKey(0);
        }
        #endregion

        #region 图像相减2:通过图像相减,查找扑克牌位置
        public static void demo2()
        {
            Mat img1 = Cv2.ImRead("../../../images/subtract1.jpg", 0);
            Mat img22 = Cv2.ImRead("../../../images/subtract2.jpg");

            Mat img2 = new Mat();
            Cv2.CvtColor(img22, img2, ColorConversionCodes.BGR2GRAY);

            Mat st = new Mat();
            Cv2.Subtract(img2, img1, st);
            //Cv2.Subtract(img1, img2, st); // 相反

            // 把小于5的像素点设为0
            for (int i = 0; i < st.Rows; ++i)
            {
                for (int j = 0; j < st.Cols; ++j)
                {
                    byte rgb = st.At<byte>(i, j);
                    if (rgb > 0 && rgb <= 5)
                        st.Set(i, j, 0);
                }
            }

            Mat threshold = new Mat();
            Cv2.Threshold(st, threshold, 50, 255, ThresholdTypes.Binary);

            Point[][] contours = new Point[][] { };
            HierarchyIndex[] hierarcy;
            Cv2.FindContours(threshold, out contours, out hierarcy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple, null);

            //List<(int, double)> areas = new List<(int, double)>();
            //for (int i = 0; i < contours.Length; i++)
            //{
            //    areas.Add((i, Cv2.ContourArea(contours[i])));
            //}
            //// 降序排序
            //var a2 = areas.OrderByDescending(x => x.Item2).ToList();
            //foreach(var are in a2)
            //{
            //    if (are.Item2 < 100)
            //        continue;
            //    Cv2.DrawContours(img22, contours, are.Item1, new Scalar(0, 0, 255), 3);
            //    myImshow("approxPolyDP", img22);
            //    Cv2.WaitKey(0);
            //}

            // TODO 截取原图,把长方形纠正
            Point[] cnt = contours[0];
            Point[] hull = Cv2.ConvexHull(cnt);
            double epsilon = 0.001 * Cv2.ArcLength(hull, true);
            Point[] simplified_cnt = Cv2.ApproxPolyDP(hull, epsilon, true);

            epsilon = 0.1 * Cv2.ArcLength(cnt, true);
            Point[] approx = Cv2.ApproxPolyDP(cnt, epsilon, true);
            Point[][] approxs = new Point[][] { approx };

            Cv2.DrawContours(img22, approxs, 0, new Scalar(255, 0, 0), 3);
            myImshow("approxPolyDP", img22);
            Cv2.WaitKey(0);
        }
        #endregion

        #region 图像相减3:通过图像相减,凸显扑克牌位置
        //  returns just the difference of the two images
        public static Mat diff(Mat img, Mat img1)
        {
            Mat diff = new Mat();
            Cv2.Absdiff(img, img1, diff);
            return diff;
        }

        // removes the background but requires three images
        public static Mat diff_remove_bg(Mat img0, Mat img, Mat img1)
        {
            Mat d1 = diff(img0, img);
            Mat d2 = diff(img, img1);
            Mat a = new Mat();
            Cv2.BitwiseAnd(d1, d2, a);
            return a;
        }

        public static void demo3()
        {
            Mat img1 = Cv2.ImRead("../../../images/subtract1.jpg", 0);
            Mat img2 = Cv2.ImRead("../../../images/subtract2.jpg", 0);
            myImshow("subtract1", img1);
            myImshow("subtract2", img2);
            Mat st = diff_remove_bg(img2, img1, img2);
            myImshow("after subtract", st);
            Cv2.WaitKey(0);
        }
        #endregion

        #region 调用摄像头,通过图像相减,标记扑克牌位置
        public static void demo4()
        {
            VideoCapture Cap = new VideoCapture();
            Cap.Open(0);
            // 判断摄像头是否成功打开
            if (!Cap.IsOpened())
            {
                Console.WriteLine("摄像头打开失败.");
                return;
            }

            /* opencv3 */
            //Cap.Set(CaptureProperty.FrameWidth, 1280);  // 设置采集的图像宽度
            //Cap.Set(CaptureProperty.FrameHeight, 720); // 设置采集的图像高度

            /* opencv4 */
            Cap.Set(VideoCaptureProperties.FrameWidth, 1280);  // 设置采集的图像宽度
            Cap.Set(VideoCaptureProperties.FrameHeight, 720); // 设置采集的图像高度
            //Cap.Set(VideoCaptureProperties.Exposure, 0); // 设置曝光值

            Mat bgimg0 = new Mat();
            Mat bgimg = new Mat();
            int frame_no = 10; // 第10帧稳定图像
            while (frame_no > 0)
            {
                if (Cap.Read(bgimg0))
                    frame_no--;
            }
            Cv2.CvtColor(bgimg0, bgimg, ColorConversionCodes.BGR2GRAY);

            Mat frame = new Mat();
            Mat gray = new Mat();
            Mat st = new Mat();
            Mat img = new Mat();
            while (true)
            {
                if (Cap.Read(frame))
                {
                    Cv2.CvtColor(frame, gray, ColorConversionCodes.BGR2GRAY);
                    Cv2.Subtract(gray, bgimg, st);

                    Mat threshold = new Mat();
                    Cv2.Threshold(st, threshold, 50, 255, ThresholdTypes.Binary);

                    Point[][] contours = new Point[][] { };
                    HierarchyIndex[] hierarcy;
                    Cv2.FindContours(threshold, out contours, out hierarcy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple, null);

                    Cv2.DrawContours(st, contours, -1, new Scalar(255, 255, 255), 3);
                    img = st;

                    for (int i = 0; i < contours.Length; i++)
                    {
                        var area = Cv2.ContourArea(contours[i]);
                        if (area < 200)
                            continue;

                        double peri = Cv2.ArcLength(contours[i], true);
                        Point[] approx = Cv2.ApproxPolyDP(contours[i], 0.04 * peri, true);
                        if (approx.Length == 4)
                        {
                            Rect rect = Cv2.BoundingRect(approx);
                            Cv2.Rectangle(frame, new Point(rect.X, rect.Y),
                                new Point(rect.X + rect.Width, rect.Y + rect.Height),
                                new Scalar(0, 0, 255), 2);
                        }
                    }

                    // TODO 对比前几/十几帧,新放一张扑克,知道是那张
                    // 等待图像稳定,不放牌后,再计算
                    myImshow("frame", frame);
                    myImshow("subtract", img);
                    myImshow("threshold", threshold);

                    Cv2.WaitKey(1);
                }
            }
        }
        #endregion
    }
}


C++版本运行代码如下:

#include <opencv2/opencv.hpp>
#include <opencv2/cvconfig.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>    

#include <io.h>
#include <string>
#include <iostream>

using namespace cv;
using namespace std;

void myImshow(string name, Mat img)
{
    Mat temp;
    cv::resize(img, temp, Size(img.cols * 1, img.rows * 1), 0, 0, 3);
    cv::imshow(name, temp);
}

// 图像相减1:图像的减法运算
void demo1()
{
    Mat img1 = cv::imread("../images/subtract1.jpg", 0); // 灰度图
    Mat img2 = cv::imread("../images/subtract2.jpg", 0); // 灰度图

    myImshow("subtract1", img1);
    myImshow("subtract2", img2);

    Mat st = img2 - img1;
    myImshow("after subtract", st);

    Mat threshold;
    cv::threshold(st, threshold, 50, 255, THRESH_BINARY);

    myImshow("after threshold", threshold);
    cv::waitKey(0);
}

// 图像相减2:通过图像相减,查找扑克牌位置
void demo2()
{
    Mat img1 = cv::imread("../images/subtract1.jpg", 0);
    Mat img22 = cv::imread("../images/subtract2.jpg");

    Mat img2;
    cv::cvtColor(img22, img2, COLOR_BGR2GRAY);

    Mat st;
    cv::subtract(img2, img1, st);
    //cv::Subtract(img1, img2, st); // 相反

    // 把小于5的像素点设为0
    for (int i = 0; i < st.rows; ++i)
    {
        for (int j = 0; j < st.cols; ++j)
        {
            char rgb = st.at<char>(i, j);
            if (rgb > 0 && rgb <= 5)
                st.at<char>(i, j) = 0;
        }
    }

    Mat threshold;
    cv::threshold(st, threshold, 50, 255, THRESH_BINARY);

    vector<vector<Point>> contours;
    vector<Vec4i> hierarcy;
    findContours(threshold, contours, hierarcy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));

    //for (int i = 0; i < contours.size(); i++)
    //{
    //    int area = cv::contourArea(contours[i]);
    //    if (area < 100)
    //        continue;

    //    cv::drawContours(img22, contours, i, Scalar(0, 0, 255), 3);
    //    myImshow("approxPolyDP", img22);
    //    cv::waitKey(0);
    //}

    // TODO 截取原图,把长方形纠正
    vector<Point> cnt = contours[0];
    vector<Point> hull;
    cv::convexHull(cnt, hull);
    double epsilon = 0.001 * cv::arcLength(hull, true);
    std::vector<cv::Point> simplified_cnt;
    cv::approxPolyDP(hull, simplified_cnt, epsilon, true);

    epsilon = 0.1 * cv::arcLength(cnt, true);
    vector<Point> approx;
    cv::approxPolyDP(cnt, approx, epsilon, true);
    vector<vector<Point>> approxs;
    approxs.push_back(approx);

    cv::drawContours(img22, approxs, 0, Scalar(255, 0, 0), 3);
    myImshow("approxPolyDP", img22);
    cv::waitKey(0);
}

//  returns just the difference of the two images
Mat diff(Mat img, Mat img1)
{
    Mat diff;
    cv::absdiff(img, img1, diff);
    return diff;
}
// removes the background but requires three images
Mat diff_remove_bg(Mat img0, Mat img, Mat img1)
{
    Mat d1 = diff(img0, img);
    Mat d2 = diff(img, img1);
    Mat a;
    cv::bitwise_and(d1, d2, a);
    return a;
}
// 图像相减3:通过图像相减,凸显扑克牌位置
void demo3()
{
    Mat img1 = cv::imread("../images/subtract1.jpg", 0);
    Mat img2 = cv::imread("../images/subtract2.jpg", 0);
    myImshow("subtract1", img1);
    myImshow("subtract2", img2);
    Mat st = diff_remove_bg(img2, img1, img2);
    myImshow("after subtract", st);
    cv::waitKey(0);
}

// 调用摄像头,通过图像相减,标记扑克牌位置
void demo4()
{
    VideoCapture cap;
    cap.open(0);
    if (!cap.isOpened())
    {
        cout << "摄像头打开失败." << endl;
        while (true);
        return;
    }

    //cap.set(CAP_PROP_FRAME_WIDTH, 1280);  // 宽度
    //cap.set(CAP_PROP_FRAME_HEIGHT, 720); // 高度
    //cap.set(CAP_PROP_EXPOSURE, 0);     // 曝光

    Mat bgimg0;
    Mat bgimg;
    int frame_no = 10; // 第10帧稳定图像
    while (frame_no > 0)
    {
        cap >> bgimg0;
        if (!bgimg0.empty())
        {
            frame_no--;
        }
    }
    cv::cvtColor(bgimg0, bgimg, COLOR_BGR2GRAY);

    Mat frame;
    Mat gray;
    Mat st;
    Mat img;
    while (true)
    {
        cap >> frame;
        if (!frame.empty())
        {
            cv::cvtColor(frame, gray, COLOR_BGR2GRAY);
            cv::subtract(gray, bgimg, st);

            Mat threshold;
            cv::threshold(st, threshold, 50, 255, THRESH_BINARY);

            vector<vector<Point>> contours;
            vector<Vec4i> hierarcy;
            findContours(threshold, contours, hierarcy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
            cv::drawContours(st, contours, -1, Scalar(255, 255, 255), 3);
            img = st;

            for (int i = 0; i < contours.size(); i++)
            {
                int area = cv::contourArea(contours[i]);
                if (area < 200)
                    continue;

                double peri = cv::arcLength(contours[i], true);
                vector<Point> approx;
                cv::approxPolyDP(contours[i], approx, 0.04 * peri, true);
                if (approx.size() == 4)
                {
                    Rect rect = cv::boundingRect(approx);
                    cv::rectangle(frame, Point(rect.x, rect.y),
                        Point(rect.x + rect.width, rect.y + rect.height),
                        Scalar(0, 0, 255), 2);
                }
            }

            // TODO 对比前几/十几帧,新放一张扑克,知道是那张
            // 等待图像稳定,不放牌后,再计算
            myImshow("frame", frame);
            myImshow("subtract", img);
            myImshow("threshold", threshold);

            cv::waitKey(1);
        }
    }
}

int main()
{
    demo1();
    //demo2();
    //demo3();
    //demo4();
}


Python版本运行效果及代码如下:

demo1.py:图像的减法运算:

import cv2

# img1=cv2.imread('../images/subtract1.jpg')
img1 = cv2.imread('../images/subtract1.jpg', 0)  # 灰度图
# img2=cv2.imread('../images/subtract2.jpg')
img2 = cv2.imread('../images/subtract2.jpg', 0)

cv2.imshow('subtract1', img1)
cv2.imshow('subtract2', img2)

#
st = img2 - img1
# st=img1-img2#相反
cv2.imshow('after subtract', st)

# 效果好一点
# ret,threshold=cv2.threshold(st,0, 127, cv2.THRESH_BINARY)
ret, threshold = cv2.threshold(st, 50, 255, cv2.THRESH_BINARY)
cv2.imshow('after threshold', threshold)

cv2.waitKey(0)


demo2.py:通过图像相减,查找扑克牌位置:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# img1=cv2.imread('../images/subtract1.jpg')
img1 = cv2.imread('../images/subtract1.jpg', 0)  # 灰度图
# img2=cv2.imread('../images/subtract2.jpg')
# img2 = cv2.imread('../images/subtract2.jpg', 0)
img22 = cv2.imread('../images/subtract2.jpg')
img2 = cv2.cvtColor(img22, cv2.COLOR_BGR2GRAY)

# cv2.imshow('subtract1', img1)
# cv2.imshow('subtract2', img2)

#
st = cv2.subtract(img2, img1)
# st = cv2.subtract(img1, img2)#相反
st[st <= 5] = 0  # 把小于20的像素点设为0

# cv2.imshow('after subtract', st)

'''
# 直方图,看看大部分像素集中在哪个区域
# plt.plot(st)
pxs = st.ravel()
pxs=[x for x in pxs if x>5]#20,10
plt.hist(pxs, 256, [0, 256])
plt.show()
'''

# 效果好一点
# ret,threshold=cv2.threshold(st,0, 127, cv2.THRESH_BINARY)
ret, threshold = cv2.threshold(st, 50, 255, cv2.THRESH_BINARY)
# cv2.imshow('after threshold', threshold)

contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

areas = list()
for i, cnt in enumerate(contours):
    areas.append((i, cv2.contourArea(cnt)))

#
a2 = sorted(areas, key=lambda d: d[1], reverse=True)

'''
for i,are in a2:
    if are <100:
        continue
    cv2.drawContours(img22, contours, i, (0, 0, 255), 3)
    print(i,are)

    cv2.imshow('drawContours',img22)
    cv2.waitKey(0)
# cv2.destroyAllWindows()
'''

# TODO 截取原图,把长方形纠正
cnt = contours[0]
print(cnt)
hull = cv2.convexHull(cnt)
epsilon = 0.001 * cv2.arcLength(hull, True)
simplified_cnt = cv2.approxPolyDP(hull, epsilon, True)

epsilon = 0.1 * cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
print(approx)
cv2.drawContours(img22, [approx], 0, (255, 0, 0), 3)
cv2.imshow('approxPolyDP', img22)
cv2.waitKey(0)
exit(3)

# findHomography(srcPoints, dstPoints, method=None, ransacReprojThreshold=None, mask=None, maxIters=None, confidence=None)
# H = cv2.findHomography(srcPoints=cnt.astype('single'), dstPoints=np.array([[[0., 0.]], [[2150., 0.]], [[2150., 2800.]], [[0., 2800.]]]))
# M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)


# now that we have our screen contour, we need to determine
# the top-left, top-right, bottom-right, and bottom-left
# points so that we can later warp the image -- we'll start
# by reshaping our contour to be our finals and initializing
# our output rectangle in top-left, top-right, bottom-right,
# and bottom-left order
pts = approx.reshape(4, 2)
rect = np.zeros((4, 2), dtype="float32")

# the top-left point has the smallest sum whereas the
# bottom-right has the largest sum
s = pts.sum(axis=1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]

# compute the difference between the points -- the top-right
# will have the minumum difference and the bottom-left will
# have the maximum difference
diff = np.diff(pts, axis=1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]

# multiply the rectangle by the original ratio
ratio = image.shape[0] / 300.0
rect *= ratio

# now that we have our rectangle of points, let's compute
# the width of our new image
(tl, tr, br, bl) = rect
widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))

# ...and now for the height of our new image
heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))

# take the maximum of the width and height values to reach
# our final dimensions
maxWidth = max(int(widthA), int(widthB))
maxHeight = max(int(heightA), int(heightB))

# construct our destination points which will be used to
# map the screen to a top-down, "birds eye" view
dst = np.array([
    [0, 0],
    [maxWidth - 1, 0],
    [maxWidth - 1, maxHeight - 1],
    [0, maxHeight - 1]], dtype="float32")

# calculate the perspective transform matrix and warp
# the perspective to grab the screen
M = cv2.getPerspectiveTransform(rect, dst)
warp = cv2.warpPerspective(img22, M, (maxWidth, maxHeight))

# final_image = cv2.warpPerspective(img22, H, (2150, 2800))

cv2.imshow('final_image', warp)
cv2.waitKey(0)


demo3.py:通过图像相减,凸显扑克牌位置:

"""
图像相减3.py:

3张图片

"""
import cv2

def diff(img, img1):  # returns just the difference of the two images
    return cv2.absdiff(img, img1)


def diff_remove_bg(img0, img, img1):  # removes the background but requires three images
    d1 = diff(img0, img)
    d2 = diff(img, img1)
    return cv2.bitwise_and(d1, d2)


# img1=cv2.imread('subtract1.jpg')
img1 = cv2.imread('subtract1.jpg', 0)  # 灰度图
# img2=cv2.imread('subtract2.jpg')
img2 = cv2.imread('subtract2.jpg', 0)

cv2.imshow('subtract1', img1)
cv2.imshow('subtract2', img2)

st = diff_remove_bg(img2, img1,img2)
cv2.imshow('after subtract', st)

cv2.waitKey(0)


demo4.py:调用摄像头,通过图像相减,标记扑克牌位置:

import cv2
import numpy as np

def myImshow(name,img):
    imgH = img.shape[0]
    imgW = img.shape[1]
    temp = cv2.resize(img, ((int)(imgW*0.5), (int)(imgH*0.5)), interpolation = cv2.INTER_NEAREST)
    cv2.imshow(name, temp)

# 外部摄像头默认好像是CAP_MSMF格式,会导致摄像头无法打开,设置成CAP_DSHOW就可以了
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
#ret = cap.set(3, 640)
#ret = cap.set(4, 480)

ret =  cap.set(cv2.CAP_PROP_FRAME_WIDTH,1280)  # 设置图像宽
ret =  cap.set(cv2.CAP_PROP_FRAME_HEIGHT,720) # 设置图像高
ret =  cap.set(cv2.CAP_PROP_EXPOSURE, 0)     # 设置曝光值

cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
cap.read()
'''
cal=[cap.read()[1] for x in range(20)]

#mean 直接的加减是不行的
# bgimg0=np.mean(np.sum(cal))
# bgimg0=np.average(cal)
# bgimg0=np.mean(cal)
nps1=sum(cal)
mean1=nps1/len(cal)
# mean1[mean1<0]=0
# mean1[mean1>255]=255
cv2.imshow('bgimg', mean1)
cv2.waitKey(0)
exit(3)
'''

frame_no = 100
# cap.set(1, frame_no)#第10帧
ret, bgimg0 = cap.read()  # 背景
bgimg = cv2.cvtColor(bgimg0, cv2.COLOR_BGR2GRAY)
myImshow('bgimg' + str(frame_no), bgimg0)
# cv2.imwrite('desk_bgimg.jpg',bgimg)

while cap.isOpened():
    ret, frame = cap.read()  # TODO 图像稳定
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    #
    st = cv2.subtract(gray, bgimg)
    # st = cv2.subtract(img1, img2)#相反
    # st[st <= 5] = 0  # 把小于20的像素点设为0

    ret, threshold = cv2.threshold(st, 50, 255, cv2.THRESH_BINARY)
    contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    print("contours size: ", len(contours))

    # img = cv2.drawContours(st, contours, -1, (0, 0, 0), 13)
    img = cv2.drawContours(st, contours, -1, (255, 255, 255), 3)
    #
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area < 200:
            continue

        peri = cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, 0.04 * peri, True)
        if len(approx) == 4:
            (x, y, w, h) = cv2.boundingRect(approx)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)

    # TODO 对比前几/十几帧,新放一张扑克,知道是那张
    # 等待图像稳定,不放牌后,再计算

    myImshow("frame", frame)
    myImshow("subtract", img)
    # cv2.moveWindow("subtract", y=bgimg.shape[0], x=0)
    myImshow('threshold', threshold)
    # cv2.moveWindow("threshold", x=bgimg.shape[1], y=0)

    key = cv2.waitKey(delay=1)
    if key == ord("q"):
        break
    elif key == ord("s"):
        cv2.imwrite('poker-threshold.jpg', threshold)

cv2.destroyAllWindows()