【问题标题】:random matrix with restrictions有限制的随机矩阵
【发布时间】:2014-03-12 14:55:41
【问题描述】:

我想生成一个随机矩阵,它的元素应该只有 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 标记!

【问题讨论】:

  • 你想要0和1的随机分布,还是限制?您的 x% 和 100-x% 1s 和 0s 非常简单:使用 randu 而不是 randn 值从 0 到 100,然后将所有值
  • 使用限制的一种方法是这样做:创建一个具有 70% 30% 分布的随机矩阵。然后调用一个测试你的限制的方法:计算对角线元素,计算中心和/或角落的 0。如果矩阵通过了您的测试,请接受它。否则:创建另一个随机矩阵并对其进行测试。
  • 我会尝试用所需比例的 1 和 0 填充一个数组,然后将它们随机排列以维持或建立您的限制标准。

标签: c++ opencv random


【解决方案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

再见,

弗朗西斯

【讨论】:

    猜你喜欢
    • 2014-09-01
    • 1970-01-01
    • 2022-12-03
    • 2021-02-09
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多