【问题标题】:How to find each black bar's begin and end row numbers?如何找到每个黑条的开始和结束行号?
【发布时间】:2016-12-24 07:11:25
【问题描述】:

cv::Mat 二值化图像。 在垂直方向找到每个黑条的行号。

【问题讨论】:

  • 有趣的问题。到目前为止你有没有尝试过?
  • @MarkSetchell 是的。谢谢。

标签: c++ opencv image-processing


【解决方案1】:

img 是问题中的给定图片。

我是这样编码的。

Mat img_inv;
bitwise_not(img, img_inv);

int totalrows = img_inv.rows;
int totalcols = img_inv.cols;

int hist[totalrows];
int blackspacecount = 0;
bool isbackground = true;

for(int i=0; i<totalrows; i++)
{
    hist[i] = countNonZero(img_inv(Rect(0,i,totalcols,1)));

    if(hist[i] > 0)
    {
        if(isbackground == true)
        {
            blackspacecount++;
            isbackground = false;
        }
    }
    else
    {
        isbackground = true;
    }
}



int blackspaces[blackspacecount][2];

int p = 0;

for(int i=1; i<totalrows; i++)
{
    if ( hist[i] > 0 && hist[i-1] == 0)
    {
        blackspaces[p][0] = i;    // Begin
    }
    if ( hist[i] == 0 && hist[i-1] > 0)
    {
        blackspaces[p][1] = i-1;    // End
        p++;
    }
}

还有其他方法吗?

【讨论】:

    【解决方案2】:

    我认为您要求计算图像中每个黑色像素的长度,您可以通过使用指针扫描图像来计算长度。当我们使用指向图像的指针时,指针指向第一行。这是代码

    Mat image; //this is the image that contain the above image;
    int numberOfRow=image.rows;//number of rows in the image
    int length[4];
    int forTheFirstTime=0;
    int index=0;
    int a=0;
    for(int j=0;j<numberOfRow;j++)
    {
      uchar* data=image.ptr<uchar>(j);//the pointer to each row in the image
      if(data[0]==0) //if the pixel at the first is black
      {
        a++;  
      }
      if(data[0]==1)
      {
        if(forTheFirstTime==0)//if the white pixel is for the first time
        {
          length[index]=a;
          a=0;
          index++
        }
        else
        {
          //do nothing
        }
      }
    }
    

    更多搜索谷歌扫描带指针的图片。

    【讨论】:

    • 感谢您告知image.ptr
    猜你喜欢
    • 2021-04-14
    • 2020-12-02
    • 1970-01-01
    • 2013-07-31
    • 2016-05-02
    • 2012-10-18
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    相关资源
    最近更新 更多