2014-03-12 59 views
2

我想生成一个随机矩阵,它的元素应该只有1或0,我必须要通过相当多的类似限制:1秒的数字或有限制的随机矩阵

  1. 号码0的相同70%0 30%1S
  2. 大部分的0在一个角落或在基体的中心部分
  3. 0避免像对角线或矩形

的目的是给像的图形表示共同的模式AC hessboard,许多矩阵必须随机生成并显示给用户。

因此,我使用了opencv2中的cv :: Mat,这正是我需要的图形表示,但对随机限制并不舒服;我的代码:

Mat mean = Mat::zeros(1,1,CV_32FC1); 
Mat sigma= Mat::ones(1,1,CV_32FC1); 
Mat resized = Mat(300,300,CV_32FC3); 
Mat thr; 
lotAreaMat = Mat(lotAreaWidth,lotAreaHeight,CV_32FC3); 
randn(lotAreaMat, mean, sigma); 
resize(lotAreaMat, resized, resized.size(), 0, 0, cv::INTER_NEAREST); 

Mat grey;// = resized.clone(); 
cvtColor(resized,grey,CV_RGB2GRAY); 
threshold(grey,thr,0.2,255,THRESH_BINARY_INV); 

这里的问题是,我不知道如何定义一个随机生成器模式,一些想法?

这些矩阵的图形表示看起来像AR-Markers!

+0

你想拥有rando m分配0s和1s还是限制? 您的x%和100-x%1s和0s非常简单:使用'randu'而不是'randn',其值为0到100,然后将所有值 Micka

+0

使用限制的一种方法是执行此操作: 使用70%30%的分布创建一个随机矩阵。然后调用一个测试您的限制的方法:计算对角元素,在中心和/或角落计数0。如果矩阵通过了你的测试,接受它。否则:创建另一个随机矩阵并对其进行测试。 – Micka

+0

我会尝试用1和0的比例填充数组,然后将它们混合以维护或建立您的限制条件。 – pjs

回答

1

几乎没有机会在opencv中准确找到想要的功能。你也可以通过一个访问像素之一,使用rand()http://www.cplusplus.com/reference/cstdlib/rand/

这是一个起点,绘制类似随机点的盘:

#include<iostream> 
#include<cmath> 

#include <stdio.h>  /* printf, scanf, puts, NULL */ 
#include <stdlib.h>  /* srand, rand */ 
#include <time.h>  /* time */ 

#include<opencv2/imgproc/imgproc.hpp> 
#include<opencv2/highgui/highgui.hpp> 
#include <opencv2/core/core.hpp> 
using namespace std; 
using namespace cv; 

uchar getrandom(double probazero){ 
    int bla=rand(); 
    if(probazero*RAND_MAX>bla){ 
     return 0; 
    } 
    return 255; 
} 

int main() 

{ 
    srand(time(NULL)); 
    int sizex=420; 
    int sizey=420; 
    Mat A = Mat(sizex,sizey,CV_8UC1); 

    double dx=2.0/A.cols; 
    double dy=2.0/A.rows; 
    double y=-dy*(A.rows*0.5); 
    uchar *input = (uchar*)(A.data); 
    for(int j = 0;j < A.rows;j++){ 
     double x=-dx*(A.cols*0.5); 
     for(int i = 0;i < A.cols;i++){ 
          // x*x+y*y is square of radius 
      input[A.step * j + i ]=getrandom(x*x+y*y) ; 
      x+=dx; 
     } 
     y+=dy; 
    } 

    imwrite("out.png",A); 
    A.release(); 

    return 0; 
} 

编译:

gcc -fPIC main3.cpp -o main3 -lopencv_highgui -lopencv_imgproc -lopencv_core -I /usr/local/include 

再见,

Francis