2013-06-17 2 views
0

Я пытаюсь получить изображение с высоты птичьего полета. Я изменяю интенсивность пикселей в двух для петель, идущих по строке и столбцу соответственно.Ошибка сегментации (сбрасывание ядра) при обработке пикселей

birdeyeview_img.at<uchar>(p,q)=(int)undistor_img.at<uchar>(round(corr_x),round(corr_y); 

Я получаю: Segmentation Fault (Core Dumped). Как изменить интенсивность пикселей, не получив такую ​​ошибку? Мое неискаженное изображение - изображение в оттенках серого. Теперь я сделал несколько изменений, он работает, но не дает должного результата, только часть кода показывает пиксельные манипуляции: //

This code will take undistorted images as input and give the bird's eye view using them 
// First we need to calculate the homography matrix 
#include "opencv2/highgui/highgui.hpp" 
#include "opencv2/core/core.hpp" 
#include "opencv2/imgproc/imgproc_c.h" 
#include <iostream> 
#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 

using namespace cv; 
using namespace std; 

int main() 
{ 
//loading the undistorted image 
Mat undistor_img=imread("undistorted images/img_u1.jpg", CV_WINDOW_AUTOSIZE); 
namedWindow("undistorted image"); 
imshow("undistorted image",undistor_img); 

// storing the resolution values 
float resolution_x=50, resolution_y=50; 
// height and width for bird's eye view 
float heightBirdEyeView=500; 
float widthBirdEyeView=700; 

//camera height and tilt 
float height_camera = 125; 
float tilt_camera=12; 

float halfAngle=180; 
float pi=3.14159; 
float alpha = tilt_camera/halfAngle*pi; 


//focal length in x and y 
float focal_length_x = 354.05700; 
float focal_length_y = 353.65297; 

//generate transformation matrix 
float H1[3][3]={resolution_x,0,widthBirdEyeView/2+1, 
     0,-1*resolution_y,heightBirdEyeView, 
     0,0,1}; 
Mat transformation_matrix(3,3,CV_32FC1,H1); 
cout<<"transformation matrix="<<endl<<transformation_matrix<<endl<<endl; 

//generate top view matrix 
float H2[3][3]={height_camera/focal_length_x,0,0, 
     0,0,height_camera, 
     0,cos(alpha)/focal_length_y,sin(alpha)}; 
Mat topview_matrix(3,3,CV_32FC1,H2); 
cout<<"topview matrix="<<endl<<topview_matrix<<endl<<endl; 

//generate scale matrix 
float H3[3][3]={1,0,undistor_img.rows, 
     0,1,undistor_img.rows, 
     0,0,1}; 
Mat scale_matrix(3,3,CV_32FC1,H3); 
cout<<"scale matrix="<<endl<<scale_matrix<<endl<<endl; 

//generate the homography matrix from these matrices 
Mat homography_matrix=transformation_matrix*topview_matrix/scale_matrix; 
cout<<"homography matrix"<<endl<<homography_matrix<<endl<<endl; 
cout<<homography_matrix.at<float>(0,0)<<endl; 
//now we need transpose of homography matrix 

Mat transpose_homography_matrix(3,3,CV_32FC1); 
for(int i=0;i<3;i++) 
{ 
    for(int j=0;j<3;j++) 
    transpose_homography_matrix.at<float>(i,j)=homography_matrix.at<float>(j,i); 
} 
cout<<"transpose of homography matrix"<<endl<<transpose_homography_matrix<<endl<<endl; 

Mat birdeyeview_img(heightBirdEyeView, widthBirdEyeView,CV_32FC3); 
namedWindow("bird's eye view image"); 

Mat p_new(3,1,CV_32FC1); // this will give the coordinates in the bird's eye view 
float corrected_x,corrected_y; 
int a=0,b=0; 
// counters for if and else blocks 

//now we need matrix with coordinates of the image plane, to be projected 
for(int p=0; p<heightBirdEyeView;p++) 
{ 
    uchar* data= undistor_img.ptr<uchar>(p); 
    uchar* hdata= birdeyeview_img.ptr<uchar>(p); 
    for(int q=0;q<widthBirdEyeView;q++) 
    { 
    int M[]={q,p,1}; 
    Mat p_old(3,1,CV_32FC1,M); //holding the positions in undistorted image 
    //cout<<transpose_homography_matrix*p_old<<endl; 
    p_new=transpose_homography_matrix*p_old; 
    corrected_x=p_new.at<float>(0,0)/p_new.at<float>(2,0); 
    corrected_y=p_new.at<float>(1,0)/p_new.at<float>(2,0); 

    if (((abs(corrected_y)>=1)&&(corrected_y<=undistor_img.rows))&&((abs(corrected_x)>=1)&&(corrected_x<=undistor_img.cols)))  
      { 
    /*hdata[q]=(1- (corrected_y-floor(corrected_y)))*(1-(corrected_x-floor(corrected_x)))*data[q] 
            +(1-(corrected_y-floor(corrected_y)))*(corrected_x-floor(corrected_x))*data[q] 
            +(corrected_y-floor(corrected_y))*(1-(corrected_x-floor(corrected_x)))*data[q] 
           +(corrected_y-floor(corrected_y))*(corrected_x-floor(corrected_x))*data[q];*/ 
    hdata[q]=(1- (corrected_y-floor(corrected_y)))*(1-(corrected_x-floor(corrected_x)))*(undistor_img.at<uchar>(floor(corrected_y),floor(corrected_x)))+(1-(corrected_y-floor(corrected_y)))*(corrected_x-floor(corrected_x))*(undistor_img.at<uchar>(floor(corrected_y), ceil(corrected_x)))+(corrected_y-floor(corrected_y))*(1-(corrected_x-floor(corrected_x)))*(undistor_img.at<uchar>(ceil(corrected_y),floor(corrected_x)))+(corrected_y-floor(corrected_y))*(corrected_x-floor(corrected_x))*(undistor_img.at<uchar>(ceil(corrected_y), ceil(corrected_x))); 
    a++;} 
    else{ 
    b++; 
    hdata[q]= undistor_img.at<uchar>(p,q); 
    } 
    } 

} 
//cout<<"if was read"<<a <<"times"<<endl; 
//cout<<"else was read"<<b <<"times"<<endl; 
imshow("bird's eye view image",birdeyeview_img); 
//cout<<"input size="<<undistor_img.rows<<"X"<<undistor_img.cols<<endl; 
//cout<<"result size="<<birdeyeview_img.rows<<"X"<<birdeyeview_img.cols<<endl; 
cvWaitKey(); 
} 

В какие другие способы я могу изменить значения пикселей (в birdeyeview_img), используя значения пикселей из другого изображения (undistor_img)?

+0

Затрудняюсь ответить, если вы не разместите еще немного кода, например, строки, в которых вы размещаете birdeyeview_img, undistor_img и т. Д. – Totoro

+0

Просьба указать, по крайней мере, размер изображения, глубину и 'p',' q', 'corr_x' , 'corr_y' – Alex

+0

Если вы используете linux, вы можете использовать' ulimit -c unlimited' для получения файла дампа ядра, когда вы сталкиваетесь с segfault, а затем используйте gdb, чтобы точно определить, где он разбился: 'gdb my_awsome_app core'. Вам нужно будет скопировать с -g вариант размещения debuugsymbols в вашем приложении. Когда вы начали использовать 'gdb', используйте' bt', чтобы получить обратную передачу функций, которые вызывались до сбоя. – morynicz

ответ

1

Для этого конкретного вопроса может быть несколько вопросов, я могу предоставить только несколько из них:

  1. birdeyeview_img или undistor_img не инициализирована
  2. координаты p, q, coor_x или coor_y превышают реальное изображение размер
  3. (наименее вероятно) глубина изображения не соответствует глубине, которую вы используете для доступа

Итак, вам нужно прежде всего проверить, что ваш вопрос не является одним из вышеперечисленных.

Смежные вопросы