我正在構建一個使用OpenCV Mat的搜索算法,在這裏我將Mat轉換爲灰色圖像,然後檢查像素以便將其簽名爲可走或不可走及其座標。我使用矢量>網格。當我嘗試從網格中打印節點ID時,程序突然關閉(例如grid.grid[10][10]->NodeID
)。創建opencv Mat到2d網格
using namespace std;
int gridZise;
class location{
public:
int x;
int y;
};
class Node{
public:
int gridX;
int gridY;
bool walkable;
location worldPosition;
int NodeID;
int gCost;
int hCost;
Node *parent;
Node(bool _walkable, int _gridX, int _gridY)
{
walkable = _walkable;
gridX = _gridX;
gridY = _gridY;
NodeID = gridY * gridZise + gridX;
}
Node(int _gridX, int _gridY){
gridX = _gridX;
gridY = _gridY;
NodeID = gridY * gridZise + gridX;
}
int fCost(){
return gCost + hCost;
}
};
class Grid{
public:
cv::Mat map;
vector<vector<Node*> > grid;
int gridx;
int gridy;
Grid(cv::Mat _map){
map = _map;
gridx = map.cols;
gridy = map.cols;
gridZise = map.cols;
}
void CreateGrid(){
// Set up sizes. (HEIGHT x WIDTH)
grid.resize(gridy);
for (int i = 0; i < gridy; ++i)
grid[i].resize(gridx);
// build up the grid
for(int i=0; i <gridx;i++){
for(int j=0; j < gridy;j++){
int pixel_val = map.at<int>(i,j);
bool _walkable = false;
if(pixel_val > 120){//if the value of the pixel is bigger than 120 is walkable
_walkable = true;
}
grid[i][j]->walkable = _walkable;
grid[i][j]->gridX = i;
grid[i][j]->gridY = j;
}
}
}
void PrintGrid(){
for(int i=0; i <gridx;i++){
for(int j=0; j < gridy;j++){
cout << grid[i][j]->NodeID <<endl;
}
}
}
vector<Node> GetNeighbours(Node node)
{
vector<Node> neighbours;
for (int x = -1; x <=1; x++)
{
for (int y = -1; y <= 1; y++)
{
if (x == 0 && y == 0)
continue;
int checkX = node.gridX + x;
int checkY = node.gridY + y;
if(checkX >=0 && checkX < gridx && checkY >=0 && checkY < gridy)
{
Node neighbour(checkX,checkY);
neighbours.push_back(neighbour);
}
}
}
return neighbours;
}
Node nodeFromLocation(location _node){
Node currentNode = *grid[_node.x][_node.y];
return currentNode;
}
};
using namespace cv;
int main()
{
cv::Mat img;
img = imread("C:\\Users\\abdulla\\Pictures\\maze.jpg");
if(img.empty()){
cout<<"image not load "<<endl;
return -1;
}
cvtColor(img,img,CV_BGR2GRAY);
imshow("image",img);
waitKey();
Grid grid(img);
grid.PrintGrid();
return 0;
}
謝謝。
灰色圖像CV_8UC,所以你需要UCHAR,'UCHAR pixel_val = map.at(I,J讀取每個像素);'。你也可以用'img = imread(path,CV_LOAD_IMAGE_GRAYSCALE)'加載圖像,所以你不必再次將它轉換爲灰色。 –
嗨@Tony J,謝謝你的回覆。我確實使用了uchar而不是int。當我嘗試在網格中輸入節點的值時,問題就開始了。 'grid.grid [10] [10] .NodeID' – Ahmohamed