29447945 发表于 2020-9-21 19:04

【树莓派4B测评】+OPENCV 简单车牌定位

<div class='showpostmsg'><p>近年来,汽车车牌识别(License Plate Recognition)已经越来越受到人们的重视。特别是在智能交通系统中,汽车牌照识别发挥了巨大的作用。汽车牌照的自动识别技术是把处理图像的方法与计算机的软件技术相连接在一起,以准确识别出车牌牌照的字符为目的,将识别出的数据传送至交通实时管理系统,以最终实现交通监管的功能。在车牌自动识别系统中,从汽车图像的获取到车牌字符处理是一个复杂的过程,主要分为四个阶段:图像获取、车牌定位、字符分割以及字符识别。</p>

<p>&nbsp;</p>

<p><strong>灰度化:</strong></p>

<p>在车牌识别中我们需要将图像转化为灰度图像,这样有利于后续步骤的开展,如Soble算子只能作用于灰度图像。</p>

<p>灰度化,在RGB模型中,如果R=G=B时,则彩色表示一种灰度颜色,其中R=G=B的值叫灰度值,因此,灰度图像每个像素只需一个字节存放灰度值(又称强度值、亮度值),灰度范围为0-255。</p>

<p>Opencv中函数</p>

<p><strong>void&nbsp;<tt>cvtColor</tt><big>(</big>InputArray&nbsp;src, &nbsp;OutputArray&nbsp;dst, &nbsp;int&nbsp;code, &nbsp;int&nbsp;dstCn=0&nbsp;<big>)</big></strong></p>

<p>参数详解:</p>

<p><strong>&nbsp;src:</strong>输入图像:8位无符号的16位无符号(cv_16uc&hellip;)或单精度浮点。<br />
<strong>&nbsp;dst:</strong>的大小和深度src.</p>

<p><strong>code:</strong>输出图像颜色空间转换的代码。</p>

<p><strong>dstCn:</strong>目标图像中的信道数;如果参数为0,则从SRC和代码自动导出信道的数目。</p>

<div aria-label="代码段 小部件" contenteditable="false" role="region" tabindex="-1">
<pre data-widget="codesnippet">
<code class="hljs">Mat Grayscale(Mat &amp;img) {
    Mat out;
    cvtColor(img, out, COLOR_RGB2GRAY);

    return out;
}</code></pre>
<img src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" /><span style="background: url(&quot;https://bbs.eeworld.com.cn/static/editor/plugins/widget/images/handle.png&quot;) rgba(220, 220, 220, 0.5); top: -15px; left: 0px; display: block;"><img height="15" role="presentation" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" title="点击并拖拽以移动" width="15" /></span></div>

<p>&nbsp;</p>

<p><strong>高斯模糊:</strong></p>

<p>车牌识别中利用高斯模糊将图片平滑化,去除干扰的噪声对后续图像处理的影响。</p>

<p>高斯模糊(<strong>GaussianBlur()</strong>),也叫高斯平滑。</p>

<p>周边像素的平均值,所谓&quot;模糊&quot;,可以理解成每一个像素都取周边像素的平均值。</p>

<div aria-label="代码段 小部件" contenteditable="false" role="region" tabindex="-1">
<pre data-widget="codesnippet">
<code class="hljs">Mat Gaussian(Mat &amp;img) {
    Mat out;
    GaussianBlur(img, out, Size(3, 3),
      0, 0, BORDER_DEFAULT);
    return out;

}</code></pre>
<img src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" /><span style="background: url(&quot;https://bbs.eeworld.com.cn/static/editor/plugins/widget/images/handle.png&quot;) rgba(220, 220, 220, 0.5); top: -15px; left: 0px; display: block;"><img height="15" role="presentation" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" title="点击并拖拽以移动" width="15" /></span></div>

<p><strong>Sobel算子(X方向):</strong></p>

<p>车牌定位的核心算法,水平方向上的边缘检测,检测出车牌区域。</p>

<p>主要用于获得数字图像的一阶梯度,常见的应用和物理意义是边缘检测。在技术上,它是一个离散的一阶差分算子,用来计算图像亮度函数的一阶梯度之近似值。在图像的任何一点使用此算子,将会产生该点对应的梯度矢量或是其法矢量。</p>

<p>该算子包含两组3x3的矩阵,分别为横向及纵向,将之与图像作平面卷积,即可分别得出横向及纵向的亮度差分近似值。如果以A代表原始图像,Gx及Gy分别代表经横向及纵向边缘检测的图像,其公式如下:</p>

<p><a href="http://baike.baidu.com/pic/Sobel%E7%AE%97%E5%AD%90/11000092/0/11385343fbf2b21119bc68a2c88065380dd78e48?fr=lemma&amp;ct=single" target="_blank" title=""><img alt="" src="https://images2015.cnblogs.com/blog/1047627/201706/1047627-20170611152558840-2052034497.png" /></a></p>

<p>图像的每一个像素的横向及纵向梯度近似值可用以下的公式结合,来计算梯度的大小。</p>

<p><a href="http://baike.baidu.com/pic/Sobel%E7%AE%97%E5%AD%90/11000092/0/718e25c7978d5cfed0006077?fr=lemma&amp;ct=single" target="_blank" title=""><img alt="" src="http://a.hiphotos.baidu.com/baike/s%3D220/sign=85a0a5cb3901213fcb3349de64e636f8/cdbf6c81800a19d8b48e151733fa828ba61e4616.jpg" /></a></p>

<p>可用以下公式计算梯度方向。</p>

<p><a href="http://baike.baidu.com/pic/Sobel%E7%AE%97%E5%AD%90/11000092/0/969cbf441985fda0b3b7dc71?fr=lemma&amp;ct=single" target="_blank" title=""><img alt="" src="http://e.hiphotos.baidu.com/baike/s%3D220/sign=4662f30e11dfa9ecf92e511552d1f754/023b5bb5c9ea15ce8262711bb6003af33a87b210.jpg" /></a></p>

<p>在以上例子中,如果以上的角度&Theta;等于零,即代表图像该处拥有纵向边缘,左方较右方暗。</p>

<p>&nbsp;</p>

<p>OpenCV中函数:</p>

<p><strong>void&nbsp;<tt>Sobel</tt><big>(</big>InputArray&nbsp;src, OutputArray&nbsp;dst, int&nbsp;ddepth, int&nbsp;xorder, int&nbsp;yorder, int&nbsp;ksize=3, double&nbsp;scale=1,&nbsp;double&nbsp;delta=0, int&nbsp;borderType=BORDER_DEFAULT&nbsp;<big>)</big></strong></p>

<p>参数:<br />
<strong>src:&nbsp;</strong>源图像。<br />
<strong>dst</strong>:相同大小和相同数量的通道的目标图像。<br />
<strong>ddepth</strong>:目标图像的深度。<br />
<strong>xorder</strong>:阶导数的X.<br />
<strong>yorder</strong>:阶导数的Y.<br />
<strong>ksize</strong>:扩展Sobel算子&ndash;大小。它必须是1, 3, 5,或者7。<br />
<strong>scale:</strong>计算衍生值的可选刻度因子。默认情况下,不应用缩放。看到getderivkernels()详情。<br />
<strong>delta</strong>&nbsp;:可选的delta值,在将它们存储在DST之前添加到结果中。<br />
<strong>bordertype</strong>:像素外推方法。</p>

<p><strong>convertScaleAbs()</strong>&mdash;&mdash;先缩放元素再取绝对值,最后转换格式为8bit型。</p>

<div aria-label="代码段 小部件" contenteditable="false" role="region" tabindex="-1">
<pre data-widget="codesnippet">
<code class="hljs">Mat Sobel(Mat &amp;img) {

Mat out;
                Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;

        int scale = 1;
int delta = 0;
        int ddepth = CV_16S;
        int th = 100;

       
Sobel( img, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT );
//Scharr( grad_x, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT );

//Sobel( img, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT );
//Scharr( grad_y, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
convertScaleAbs( grad_x, out );
//   convertScaleAbs( grad_y, abs_grad_y );

//   addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, out );

    // Mat out;
    // Mat grad_x, grad_y;
    // Mat abs_grad_x, abs_grad_y;

    //X方向
    //Sobel(img, grad_x, CV_16S, 1, 0, 3, 1, 1, BORDER_DEFAULT);
    //convertScaleAbs(grad_x, abs_grad_x);
    // Sobel(img, grad_x, CV_16S, 1, 0, 1, 3, 1, BORDER_DEFAULT);
    // convertScaleAbs(img, out);

    //Y方向
    //Sobel(img, grad_y, CV_16S, 0, 1, 3, 1, 1, BORDER_DEFAULT);
    //convertScaleAbs(grad_y, abs_grad_y);
    //convertScaleAbs(img, out);

    //合并
    //addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, out);

    return out;
}</code></pre>
<img src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" /><span style="background: url(&quot;https://bbs.eeworld.com.cn/static/editor/plugins/widget/images/handle.png&quot;) rgba(220, 220, 220, 0.5); top: -15px; left: 0px; display: block;"><img height="15" role="presentation" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" title="点击并拖拽以移动" width="15" /></span></div>

<p><strong>二值化:</strong></p>

<p>进一步对图像进行处理,强化目标区域,弱化背景。</p>

<p>图像的二值化,就是将图像上的像素点的灰度值设置为0或255,也就是将整个图像呈现出明显的只有黑和白的视觉效果。</p>

<p>OpenCV中函数</p>

<p><strong>double&nbsp;<tt>threshold</tt><big>(</big>InputArray&nbsp;src, OutputArray&nbsp;dst, double&nbsp;thresh, double&nbsp;maxVal, int&nbsp;thresholdType<big>)</big></strong></p>

<p>参数:<br />
<strong>src:</strong>源阵列(单通道,32位浮点8位)。<br />
<strong>dst</strong>:相同大小和类型的目标数组。<br />
<strong>thresh:</strong>门限阈值。<br />
<strong>Maxval</strong>:最大值使用的thresh_binary和thresh_binary_inv阈值类型。<br />
<strong>thresholdtype</strong>:阈值型,如下。</p>

<p>&nbsp;<strong>THRESH_BINARY</strong>&nbsp;&nbsp;当前点值大于阈值时,取Maxval,也就是第四个参数,下面再不说明,否则设置为0</p>

<p>&nbsp;<strong>THRESH_BINARY_INV</strong>&nbsp;当前点值大于阈值时,设置为0,否则设置为Maxval</p>

<p>&nbsp;<strong>THRESH_TRUNC</strong>&nbsp;当前点值大于阈值时,设置为阈值,否则不改变</p>

<p>&nbsp;<strong>THRESH_TOZERO</strong>&nbsp;当前点值大于阈值时,不改变,否则设置为0</p>

<p>&nbsp;<strong>THRESH_TOZERO_INV&nbsp;</strong>&nbsp;当前点值大于阈值时,设置为0,否则不改变</p>

<div aria-label="代码段 小部件" contenteditable="false" role="region" tabindex="-1">
<pre data-widget="codesnippet">
<code class="hljs">Mat TwoValued(Mat &amp;img) {
    Mat out;
    threshold(img, out, 0, 255, THRESH_BINARY|THRESH_OTSU);
    //threshold(img, out, 100, 255, CV_THRESH_BINARY);

    return out;
}
</code></pre>
<img src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" /><span style="background: url(&quot;https://bbs.eeworld.com.cn/static/editor/plugins/widget/images/handle.png&quot;) rgba(220, 220, 220, 0.5); top: -15px; left: 0px; display: block;"><img height="15" role="presentation" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" title="点击并拖拽以移动" width="15" /></span></div>

<p><strong>闭操作:</strong></p>

<p>闭操作可以将目标区域连成一个整体,便于后续轮廓的提取。</p>

<p>闭操作可使轮廓线更光滑,但与开操作相反的是,闭操作通常消弥狭窄的间断和长细的鸿沟,消除小的空洞,并填补轮廓线中的断裂。</p>

<p>使用结构元素B对集合A进行闭操作,定义为</p>

<p><a href="http://baike.baidu.com/pic/%E9%97%AD%E6%93%8D%E4%BD%9C/7689850/0/aec379310a55b31961a2c69743a98226cefc17fc?fr=lemma&amp;ct=single" target="_blank" title=""><img alt="" src="http://c.hiphotos.baidu.com/baike/s%3D250/sign=429ab21cc3fdfc03e178e4bde43e87a9/aec379310a55b31961a2c69743a98226cefc17fc.jpg" /></a></p>

<p>这个公式表明,使用结构元素B对集合A的闭操作就是用B对A进行膨胀,然后用B对结果进行腐蚀。</p>

<p>&nbsp;</p>

<p>OpenCV中函数</p>

<p>void&nbsp;<tt>morphologyEx</tt><big>(</big>InputArray&nbsp;<strong>src</strong>, OutputArray&nbsp;<strong>dst</strong>, int&nbsp;<strong>op</strong>, InputArray&nbsp;<strong>element</strong>, Point&nbsp;<strong>anchor</strong>=Point(-1,-1), int&nbsp;<strong>iterations</strong>=1, int&nbsp;<strong>borderType</strong>=BORDER_CONSTANT, const Scalar&amp;&nbsp;<strong>borderValue</strong>=morphologyDefaultBorderValue()&nbsp;<big>)</big></p>

<p>参数:<br />
<strong>src</strong>:源图像。<br />
<strong>dst</strong>:相同大小和类型的目标图像。<br />
<strong>element:</strong>内核类型 &nbsp; &nbsp;用getStructuringElement函数得到。<br />
<strong>OP:</strong><br />
可以是以下形式之一的形态学操作的类型:<br />
<strong>morph_open</strong>&nbsp;-开启操作<br />
<strong>morph_close</strong>&nbsp;-闭合操作<br />
<strong>morph_gradient</strong>&nbsp;-形态学梯度<br />
<strong>morph_tophat</strong>&ldquo;顶帽&rdquo;<br />
<strong>morph_blackhat</strong>&nbsp;-&ldquo;黑帽&rdquo;<br />
<strong>iterations:</strong>侵蚀和膨胀的次数被应用。<br />
<strong>bordertype</strong>&ndash;像素外推方法。<br />
<strong>bordervalue</strong>&ndash;边界值在一个恒定的边界情况。默认值有特殊含义。</p>

<p>关注前4个参数即可,后面用默认参数。</p>

<div aria-label="代码段 小部件" contenteditable="false" role="region" tabindex="-1">
<pre data-widget="codesnippet">
<code class="hljs">Mat Close(Mat &amp;img) {
    Mat out;
    //Mat element(5, 5, CV_8U, cv::Scalar(1));
    Mat element = getStructuringElement(MORPH_RECT, Size(17, 5));
    morphologyEx(img, out, cv::MORPH_CLOSE, element);

    return out;
}</code></pre>
<img src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" /><span style="background: url(&quot;https://bbs.eeworld.com.cn/static/editor/plugins/widget/images/handle.png&quot;) rgba(220, 220, 220, 0.5); top: -15px; left: 0px; display: block;"><img height="15" role="presentation" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" title="点击并拖拽以移动" width="15" /></span></div>

<p><strong>取轮廓:</strong></p>

<p>将前面处理的车牌目标区域提取出来。</p>

<p>相关函数:</p>

<p>查找轮廓:</p>

<p><tt>void&nbsp;<strong>findContours</strong></tt><big>(</big>InputOutputArray&nbsp;<strong>image</strong>, OutputArrayOfArrays&nbsp;<strong>contours</strong>, OutputArray&nbsp;<strong>hierarchy</strong>, int&nbsp;<strong>mode</strong>, int&nbsp;<strong>method</strong>, Point&nbsp;<strong>offset</strong>=Point()<big>)</big></p>

<p><strong>image</strong>:&nbsp;输入的 8-比特、单通道图像. 非零元素被当成 1, 0 象素值保留为 0 - 从而图像被看成二值的。为了从灰度图像中得到这样的二值图像,可以使用 cvThreshold, cvAdaptiveThreshold 或 cvCanny. 本函数改变输入图像内容。&nbsp;</p>

<p><strong>storage</strong>&nbsp;:得到的轮廓的存储容器&nbsp;<br />
<strong>first_contour</strong>&nbsp;:输出参数:包含第一个输出轮廓的指针&nbsp;<br />
<strong>header_size</strong>&nbsp;:如果 method=CV_CHAIN_CODE,则序列头的大小 &gt;=sizeof(CvChain),否则 &gt;=sizeof(CvContour) .&nbsp;<br />
<strong>mode&nbsp;</strong>:<br />
提取模式.&nbsp;<br />
CV_RETR_EXTERNAL - 只提取最外层的轮廓&nbsp;<br />
CV_RETR_LIST - 提取所有轮廓,并且放置在 list 中&nbsp;<br />
CV_RETR_CCOMP - 提取所有轮廓,并且将其组织为两层的 hierarchy: 顶层为连通域的外围边界,次层为洞的内层边界。&nbsp;<br />
CV_RETR_TREE - 提取所有轮廓,并且重构嵌套轮廓的全部 hierarchy&nbsp;<br />
<strong>method&nbsp;</strong>:<br />
逼近方法 (对所有节点, 不包括使用内部逼近的 CV_RETR_RUNS).&nbsp;<br />
CV_CHAIN_CODE - Freeman 链码的输出轮廓. 其它方法输出多边形(定点序列).&nbsp;<br />
CV_CHAIN_APPROX_NONE - 将所有点由链码形式翻译(转化)为点序列形式&nbsp;<br />
CV_CHAIN_APPROX_SIMPLE - 压缩水平、垂直和对角分割,即函数只保留末端的象素点;&nbsp;<br />
CV_CHAIN_APPROX_TC89_L1,&nbsp;<br />
CV_CHAIN_APPROX_TC89_KCOS - 应用 Teh-Chin 链逼近算法. CV_LINK_RUNS - 通过连接为 1 的水平碎片使用完全不同的轮廓提取算法。仅有 CV_RETR_LIST 提取模式可以在本方法中应用.&nbsp;<br />
<strong>offset</strong>&nbsp;:<br />
每一个轮廓点的偏移量. 当轮廓是从图像 ROI 中提取出来的时候,使用偏移量有用,因为可以从整个图像上下文来对轮廓做分析.&nbsp;<br />
函数 cvFindContours 从二值图像中提取轮廓,并且返回提取轮廓的数目。指针 first_contour 的内容由函数填写。它包含第一个最外层轮廓的指针,如果指针为 NULL,则没有检测到轮廓(比如图像是全黑的)。其它轮廓可以从 first_contour 利用 h_next 和 v_next 链接访问到。 在 cvDrawContours 的样例显示如何使用轮廓来进行连通域的检测。轮廓也可以用来做形状分析和对象识别 - 见CVPR2001 教程中的 squares 样例。该教程可以在 SourceForge 网站上找到。&nbsp;</p>

<p>绘制轮廓:</p>

<p>void&nbsp;<strong><tt>drawContours</tt></strong><big>(</big>InputOutputArray&nbsp;<strong>image</strong>, InputArrayOfArrays&nbsp;<strong>contours</strong>, int&nbsp;<strong>contourIdx</strong>, const Scalar&amp;&nbsp;<strong>color</strong>, int<strong>thickness</strong>=1, int&nbsp;<strong>lineType</strong>=8, InputArray&nbsp;<strong>hierarchy</strong>=noArray(), int&nbsp;<strong>maxLevel</strong>=INT_MAX, Point&nbsp;<strong>offset</strong>=Point()&nbsp;<big>)</big></p>

<div aria-label="代码段 小部件" contenteditable="false" role="region" tabindex="-1">
<pre data-widget="codesnippet">
<code class="hljs">
void Contour(Mat &amp;img, Mat &amp;out) {
    RNG rng(12345);
       
    // vector&lt; Mat &gt; contours(1000);
    // vector&lt;Vec4i&gt; hierarchy(1000);
        vector&lt;vector&lt;Point&gt;&gt; contours;
    vector&lt;Vec4i&gt; hierarchy;
    findContours(img, contours, hierarchy, 3, 2, Point(0, 0));

//         return ;
    vector&lt; vector&lt;Point&gt; &gt;::iterator itc = contours.begin();
    vector&lt;RotatedRect&gt; rects;
    int t = 0;
    while (itc != contours.end()) {
      //Create bounding rect of object
      RotatedRect mr = minAreaRect(Mat(*itc));
      //large the rect for more
      if (!verifySizes(mr)) {
            itc = contours.erase(itc);
      }
      else {
            ++itc;
            rects.push_back(mr);
      }
   }
       
    cv::Mat result;
    img.copyTo(result);
    for (int i = 0; i&lt; contours.size(); i++)
    {
      drawContours(result, contours, i, Scalar(0, 0, 255), 2, 8, vector&lt;Vec4i&gt;(), 0, Point());
      //drawContours(result, contours, i, Scalar(255), 2);
    }
    //imshow(&quot;画轮廓&quot;, out);

    for (int i = 0; i &lt; rects.size(); i++) {
      circle(result, rects.center, 3, Scalar(0, 255, 0), -1);

      float minSize = (rects.size.width &lt; rects.size.height) ? rects.size.width : rects.size.height;
      //minSize = minSize - minSize*0.5;

      srand(time(NULL));
      Mat mask;
      mask.create(out.rows + 2, out.cols + 2, CV_8UC1);
      mask = Scalar::all(0);
      int loDiff = 30;
      int upDiff = 30;
      int connectivity = 4;
      int newMaskVal = 255;
      int NumSeeds = 10;
      Rect ccomp;
      int flags = connectivity + (newMaskVal &lt;&lt; 8) + (1 &lt;&lt; 16) + (1 &lt;&lt; 17);

      for (int j = 0; j &lt; NumSeeds; j++) {
            Point seed;
            seed.x = rects.center.x + rand() % (int)minSize - (minSize / 2);
            seed.y = rects.center.y + rand() % (int)minSize - (minSize / 2);
            circle(result, seed, 1, Scalar(0, 255, 255), -1);
            int area = floodFill(out, mask, seed, Scalar(255, 0, 0), &amp;ccomp, Scalar(loDiff, loDiff, loDiff), Scalar(upDiff, upDiff, upDiff), flags);
      }
      //imshow(&quot;漫水填充&quot;, mask);

      vector&lt;Point&gt; pointsInterest;
      Mat_&lt;uchar&gt;::iterator itMask = mask.begin&lt;uchar&gt;();
      Mat_&lt;uchar&gt;::iterator end = mask.end&lt;uchar&gt;();
      for (; itMask != end; ++itMask)
            if (*itMask == 255)
                pointsInterest.push_back(itMask.pos());

      RotatedRect minRect = minAreaRect(pointsInterest);

      if (verifySizes(minRect)) {
            // rotated rectangle drawing
            Point2f rect_points; minRect.points(rect_points);
            for (int j = 0; j &lt; 4; j++)
                line(result, rect_points, rect_points[(j + 1) % 4], Scalar(0, 0, 255), 1, 8);

            //Get rotation matrix
            float r = (float)minRect.size.width / (float)minRect.size.height;
            float angle = minRect.angle;
            if (r &lt; 1)
                angle = 90 + angle;
            Mat rotmat = getRotationMatrix2D(minRect.center, angle, 1);

            //Create and rotate image
            Mat img_rotated;
            warpAffine(out, img_rotated, rotmat, out.size(), 2);//实现旋转

            //Crop image
            Size rect_size = minRect.size;
            if (r &lt; 1)
                swap(rect_size.width, rect_size.height);
            Mat img_crop;
            getRectSubPix(img_rotated, rect_size, minRect.center, img_crop);

            Mat resultResized;
            resultResized.create(33, 144, CV_8UC3);
            resize(img_crop, resultResized, resultResized.size(), 0, 0, INTER_CUBIC);;

            ////Equalize croped image
            Mat grayResult;
            cvtColor(resultResized, grayResult, COLOR_BGR2GRAY);// CV_RGB2GRAY
            blur(grayResult, grayResult, Size(3, 3));
            grayResult = histeq(grayResult);

            if (1) {
                stringstream ss(stringstream::in | stringstream::out);
                ss &lt;&lt; &quot;haha&quot; &lt;&lt; &quot;_&quot; &lt;&lt; i &lt;&lt; &quot;.jpg&quot;;
                imwrite(ss.str(), grayResult);
            }

      }
    }
}</code></pre>
<img src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" /><span style="background: url(&quot;https://bbs.eeworld.com.cn/static/editor/plugins/widget/images/handle.png&quot;) rgba(220, 220, 220, 0.5); top: -15px; left: 0px; display: block;"><img height="15" role="presentation" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" title="点击并拖拽以移动" width="15" /></span></div>

<p>&nbsp;</p>

<p>最后主函数如下:</p>

<div aria-label="代码段 小部件" contenteditable="false" role="region" tabindex="-1">
<pre data-widget="codesnippet">
<code class="hljs">
int main() {
    Mat img;
    Mat out;
    //Mat result;

    //载入图片
    img = imread(&quot;car.jpg&quot;);//, CV_LOAD_IMAGE_GRAYSCALE);
    img.copyTo(out);
    //imshow (&quot;原始图&quot;, img);
   
    img = Grayscale(img);
    imshow(&quot;灰度化&quot;, img);

        img = Gaussian(img);
    imshow (&quot;高斯模糊&quot;, img);

    img = Sobel(img);
    imshow(&quot;Sobel_X&quot;, img);

    img = TwoValued(img);
    imshow(&quot;二值化&quot;, img);

    img = Close(img);
    imshow(&quot;闭操作&quot;, img);

    Contour(img, out);
       

           waitKey(0);

        destroyAllWindows();
        return 0;
}
</code></pre>
<img src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" /><span style="background: url(&quot;https://bbs.eeworld.com.cn/static/editor/plugins/widget/images/handle.png&quot;) rgba(220, 220, 220, 0.5); top: -15px; left: 0px; display: block;"><img height="15" role="presentation" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" title="点击并拖拽以移动" width="15" /></span></div>

<p>然后编写cmake文件:</p>

<div aria-label="代码段 小部件" contenteditable="false" role="region" tabindex="-1">
<pre data-widget="codesnippet">
<code class="hljs">cmake_minimum_required(VERSION 2.8)
project( test )
find_package( OpenCV REQUIRED )
add_executable( test test.cpp )
target_link_libraries( test ${OpenCV_LIBS} )</code></pre>
<img src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" /><span style="background: url(&quot;https://bbs.eeworld.com.cn/static/editor/plugins/widget/images/handle.png&quot;) rgba(220, 220, 220, 0.5); top: -15px; left: 0px; display: block;"><img height="15" role="presentation" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" title="点击并拖拽以移动" width="15" /></span></div>

<p>最后camke 和make</p>

<div aria-label="代码段 小部件" contenteditable="false" role="region" tabindex="-1">
<pre data-widget="codesnippet">
<code class="hljs">pi@raspberrypi:~/Public/OPENCV/program/Image_Identification $ cmake .
-- The C compiler identification is GNU 8.3.0
-- The CXX compiler identification is GNU 8.3.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found OpenCV: /usr/local (found version &quot;4.4.0&quot;)
-- Configuring done
-- Generating done
-- Build files have been written to: /home/pi/Public/OPENCV/program/Image_Identification
pi@raspberrypi:~/Public/OPENCV/program/Image_Identification $ make
Scanning dependencies of target test
[ 50%] Building CXX object CMakeFiles/test.dir/test.cpp.o
Linking CXX executable test
Built target test
pi@raspberrypi:~/Public/OPENCV/program/Image_Identification $
</code></pre>
<img src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" /><span style="background: url(&quot;https://bbs.eeworld.com.cn/static/editor/plugins/widget/images/handle.png&quot;) rgba(220, 220, 220, 0.5); top: -15px; left: 0px; display: block;"><img height="15" role="presentation" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" title="点击并拖拽以移动" width="15" /></span></div>

<p>运行之后界面出现如下窗口:</p>

<p>然后在工程目录下可以看到多了3个图片:</p>

<p>打开图片,可以看到已经定位到了车牌了:</p>

<p>后续就需要把数字分离并识别了</p>

<p>附上代码:</p>
</div><script>                                        var loginstr = '<div class="locked">查看本帖全部内容,请<a href="javascript:;"   style="color:#e60000" class="loginf">登录</a>或者<a href="https://bbs.eeworld.com.cn/member.php?mod=register_eeworld.php&action=wechat" style="color:#e60000" target="_blank">注册</a></div>';
                                       
                                        if(parseInt(discuz_uid)==0){
                                                                                                (function($){
                                                        var postHeight = getTextHeight(400);
                                                        $(".showpostmsg").html($(".showpostmsg").html());
                                                        $(".showpostmsg").after(loginstr);
                                                        $(".showpostmsg").css({height:postHeight,overflow:"hidden"});
                                                })(jQuery);
                                        }                </script><script type="text/javascript">(function(d,c){var a=d.createElement("script"),m=d.getElementsByTagName("script"),eewurl="//counter.eeworld.com.cn/pv/count/";a.src=eewurl+c;m.parentNode.insertBefore(a,m)})(document,523)</script>

freebsder 发表于 2020-9-21 20:25

<p>厉害了,看着C++就头疼</p>

IC爬虫 发表于 2020-9-23 20:19

<p>很棒的工作</p>

lb8820265 发表于 2020-9-23 23:31

<p>楼主厉害!,我也正在用树莓派玩OpenCV</p>

29447945 发表于 2020-9-24 09:06

lb8820265 发表于 2020-9-23 23:31
楼主厉害!,我也正在用树莓派玩OpenCV

<p>树莓派加个摄像头玩opencv很方便,有什么进展发帖一起交流哦</p>

29447945 发表于 2020-9-24 09:07

IC爬虫 发表于 2020-9-23 20:19
很棒的工作

<p>感谢支持<img height="48" src="https://bbs.eeworld.com.cn/static/editor/plugins/hkemoji/sticker/facebook/congra.gif" width="48" /></p>

29447945 发表于 2020-9-24 09:07

freebsder 发表于 2020-9-21 20:25
厉害了,看着C++就头疼

<p>哈哈哈,看多了就不疼了</p>

zhushengbing110 发表于 2020-9-24 14:34

<p>膜拜一下啊</p>
页: [1]
查看完整版本: 【树莓派4B测评】+OPENCV 简单车牌定位