c++ - 有限制的随机矩阵

标签 c++ opencv random

我想生成一个随机矩阵,它的元素应该只有 1 或 0,我必须通过很多限制,例如:

  1. 0 的数量等于 1 的数量或 70% 0 30% 1
  2. 大部分0在矩阵的角落或中心部分
  3. 0 避免使用常见的图案,例如对角线或矩形

目的是给出象棋盘一样的图形表示,必须随机生成许多矩阵并显示给用户。

因此,我使用了来自 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 标记!

最佳答案

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

再见,

弗朗西斯

关于c++ - 有限制的随机矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22355345/

相关文章:

c++ - 如何通过某个字段将对象插入到 map 结构中?

java - 如何在 OpenCv 中从图像中识别人

android - 在 Android 中选择 random 或 urandom 作为 SecureRandom 的来源

c++ - 以无符号为模的数组环绕

java - 日期的唯一值

c++ - 是否可以在循环中写入多个二进制文件

c++ - 是否可以覆盖在 C++ 中获取结构成员的默认行为?

c++ - 另一个 : Passing Vector of Structs to Function - C++, MinGW

visual-c++ - OpenCV和包含文件

java - opencv_core.Mat 与 opencv.core.Mat 之间的区别以及如何相互转换?