以下代码中的想法是让一堆“流浪者”对象缓慢地将图像“绘制”到画布上。问题是,这段代码似乎只适用于方形图像(在代码中,方形图像被标识为“隐藏”(因为它是由“画家”揭开的)并且它是从名为“UncoverTest”的文件中加载的.png"),而不是矩形的,这对我来说很神秘。尝试使用除正方形以外的任何东西时出现分段错误错误。据我所知,当我进入循环遍历 Agent 类型的向量(在行for (vector<Agent>::iterator iter = agents.begin(); iter != agents.end();++iter)
)时,会出现分段错误错误。
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <vector>
using namespace std;
using namespace cv;
//#define WINDOW_SIZE 500
#define STEP_SIZE 10.0
#define NUM_AGENTS 100
/********************/
/* Agent class definition and class prototypes */
/********************/
class Agent {
public:
Agent();
int * GetLocation(void);
void Move(void);
void Draw(Mat image);
int * GetSize(void);
private:
double UnifRand(void);
int * location;
int * GetReveal(void);
Mat hidden;
};
int * Agent::GetSize(void) {
int * size = new int[2];
size[0] = hidden.cols;
size[1] = hidden.rows;
return (size);
}
int * Agent::GetReveal(void) {
int * BGR = new int[3];
location = GetLocation();
for (int i = 0; i < 3; i++) {
BGR[i] = hidden.data[hidden.step[0]*location[0] + hidden.step[1]*location[1] + i];
}
return (BGR);
}
void Agent::Draw(Mat image) {
int * location = GetLocation();
int * color = GetReveal();
for (int i = 0;i < 3;i++) {
image.data[image.step[0]*location[0] + image.step[1]*location[1] + i] = color[i];
}
}
void Agent::Move(void) {
int dx = (int)(STEP_SIZE*UnifRand() - STEP_SIZE/2);
int dy = (int)(STEP_SIZE*UnifRand() - STEP_SIZE/2);
location[0] += (((location[0] + dx >= 0) & (location[0] + dx < hidden.cols)) ? dx : 0);
location[1] += (((location[1] + dy >= 0) & (location[1] + dy < hidden.rows)) ? dy : 0);
}
Agent::Agent() {
location = new int[2];
hidden = imread("UncoverTest.png",1);
location[0] = (int)(UnifRand()*hidden.cols);
location[1] = (int)(UnifRand()*hidden.rows);
}
double Agent::UnifRand(void) {
return (rand()/(double(RAND_MAX)));
}
int * Agent::GetLocation(void) {
return (location);
}
/********************/
/* Function prototypes unrelated to the Agent class */
/********************/
void DrawAgents(void);
/********************/
/* Main function */
/********************/
int main(void) {
DrawAgents();
return (0);
}
void DrawAgents(void) {
vector<Agent> agents;
int * size = new int[2];
Mat image;
for (int i = 0; i < NUM_AGENTS; i++) {
Agent * a = new Agent();
agents.push_back(* a);
if (i == 0) {
size = (* a).GetSize();
}
}
// cout << size[0] << " " << size[1] << endl;
image = Mat::zeros(size[0],size[1],CV_8UC3);
cvNamedWindow("Agent Example",CV_WINDOW_AUTOSIZE);
cvMoveWindow("Agent Example",100,100);
for (int stop = 1;stop != 27;stop = cvWaitKey(41)) {
for (vector<Agent>::iterator iter = agents.begin(); iter != agents.end();++iter) {
(* iter).Move();
(* iter).Draw(image);
} imshow("Agent Example",image);
}
}
谁能向我解释这个错误是如何出现在方形图像上的,以及如何解决这个问题?