Fatal error lnk1136 недопустимый или поврежденный файл

Урок №6 NeHe — Наложение текстуры В этом уроке с «Народного учебника по OpenGL» используется библиотека GLaux, из-за которой построение проекта завершается ошибкой — «Microsoft Visual Studio 9.0VClibglaux.lib : fatal error LNK1136: недопустимый или поврежденный файл». Вопрос: чем заменить эту штуку? Или как это исправить? Ссылка на урок: Урок 6. Наложение текстуры. я бы […]

Содержание

  1. Урок №6 NeHe — Наложение текстуры
  2. Fatal error lnk1136 недопустимый или поврежденный файл
  3. Answered by:
  4. Question

Урок №6 NeHe — Наложение текстуры

В этом уроке с «Народного учебника по OpenGL» используется библиотека GLaux, из-за которой построение проекта завершается ошибкой — «Microsoft Visual Studio 9.0VClibglaux.lib : fatal error LNK1136: недопустимый или поврежденный файл». Вопрос: чем заменить эту штуку? Или как это исправить? Ссылка на урок: Урок 6. Наложение текстуры.

я бы в сторону DevIL глянул, как начал с того урока его юзать так до сих пор юзаю, весчь 🙂

Ну так скачай ее откуданибудь и положи в папочку Microsoft Visual Studio 9.0VClib
В NVIDIA SDK должна быть.
Ну и в Гугле офк.

Да есть она у меня — я уж не настолько нуб, проблема в том, что студия считает её повреждённой.

дык, может, поврежденная? Другую не пробовал скачать?

Во всеми одно и тоже — может у тебя найдется работающая? Застрял, понимаешь, из-за неё.

у меня нет. 🙁 Я для тестов велосипед загрузки бмп состряпал наскоро

Вот короче часть кода, отвечающае за инициализацию OpenGL и загрузку изображения:

#include
#include
#include

#pragma comment(lib, «opengl32.lib») // Ссылка на OpenGL32.lib
#pragma comment(lib, «glu32.lib») // Ссылка на Glu32.lib
#pragma comment(lib, «glaux.lib») // Ссылка на Glaux.lib

GLfloat rQuad;
GLuint texture[1]; // Место для одной текстуры

GLvoid LoadGLTextures()
<
AUX_RGBImageRec *texture1;
texture1 = auxDIBImageLoad(«Data/NeHe.bmp»);

glGenTextures(1, &texture[0]);
glBindTexture(GL_TEXTURE_2D, texture[0]);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

glTexImage2D(GL_TEXTURE_2D, 0, 3, texture1->sizeX, texture1->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, texture1->data);
>

GLvoid InitGL(GLsizei Width, GLsizei Height) // Вызвать после создания окна OpenGL
<
LoadGLTextures();
glEnable(GL_TEXTURE_2D);

glClearColor(0.0f, 0.0f, 0.4f, 0.0f); // Цвет очистки экрана
glClearDepth(1.0); // Разрешить очистку буфера глубины
glDepthFunc(GL_LEQUAL); // Тип теста глубины
glEnable(GL_DEPTH_TEST); // Разрешить тест буфера глубины

glShadeModel(GL_SMOOTH); // Разрешить плавное цветовое сглаживание
glMatrixMode(GL_PROJECTION); // Выбор матрицы проекции
glLoadIdentity(); // Умножение матрицы на единичную матрицу

// Вычислить соотношение геометрических размеров для окна
gluPerspective(45.0f, (GLfloat)Width / (GLfloat)Height, 0.1f, 100.0f);

glMatrixMode(GL_MODELVIEW); // Выбор матрицы наблюдения модели
glLoadIdentity(); // Сброс матрицы проекции
>

GLvoid DrawGLScene()
<
// Очистка экрана и буфера глубины выбранным цветом
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();

glTranslatef(-1.5f, 0.0f, -10.0f);
glRotatef(rQuad, 1.0f, 1.0f, 1.0f);

glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();

Вся проблема в структуре AUX_RGBImageRec и функции auxDIBImageLoad библиотеки GLaux. Просьба к знающим людям: исходя из данного кода программы объясните мне, пожалуйста, как всё же мне заргузить изображение?

Суть такова — тебе необходимо получить часть файла с текстурой (конкретно — ту, где «пиксели хранятся») в виде набора байт. Как ты это сделаешь — OpenGLю фиолетово.
Если не получается использовать Glaux — можешь погуглить про формат .bmp (например в википедии) — найти пример загрузки файла, понять/скопипастить/написать свое.
Или подключить какую-нить другую либу, которая будет это делать за тебя. Например тот же DevIL, что тебе советовали.
В любом из этих случаев прийдется хоть что-то прочитать, тупой копипаст вряд ли пройдет.

Если поможет — могу попробовать «на пальцах» объяснить, что имеется в виду в примере NeHe:

Больше в коде ничего не затрагивает библиотеку Glaux. Т.о. при меняя что-то другое, надо будет переписать только эти строки.

ты точно на DevIL не хочешь перейти? Любой формат практически загружает 😉

Попробуй написать инклюды в таком порядке:
#include «gl/glee.h»
#include «gl/gl.h»
#include «gl/glaux.h»

У меня скомпилилось

Помеха
Насчёт функционала этих тиопв данных и функций я всё понял. Но всё равно спасибо! Сейчас порыскаю в Википедии.
ShamaN
Я его скачал, файл называется DevIL-EndUser-1.6.5.zip. Его содержмое кидать в Windowssystem?

У Борескова сейчас почитаю, потом отпишусь.

Источник

Fatal error lnk1136 недопустимый или поврежденный файл

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

I’m now using Visual Studio 2010 and I encounter the fatal error as shown below.

Error 1 fatal error LNK1136: invalid or corrupt file C:Program Files test1

Below is my program (marr.cpp).

/* Marr/Hildreth edge detection */

#include «stdafx.h»
#include «stdio.h»
#include «cv.h»
#include «highgui.h»

#define PI 3.1415926535

/* The image header data structure */
struct header
<
int nr, nc; /* Rows and columns in the image */
int oi, oj; /* Origin */
>;

/* The IMAGE data structure */
struct image
<
struct header *info; /* Pointer to header */
unsigned char **data; /* Pixel values */
>;

#define SQRT2 1.414213562
#define BLACK 0
#define WHITE 1

long seed = 132531;
typedef struct image * IMAGE;

#if defined (MAX)
int PBM_SE_ORIGIN_COL=0, PBM_SE_ORIGIN_ROW=0;
char **arg;
int maxargs;
#else
extern int PBM_SE_ORIGIN_COL, PBM_SE_ORIGIN_ROW;
#endif

int range (IMAGE im, int i, int j);
void print_se (IMAGE p);
IMAGE Input_PBM (char *fn);
IMAGE Output_PBM (IMAGE image, char *filename);
void get_num_pbm (FILE *f, char *b, int *bi, int *res);
void pbm_getln (FILE *f, char *b);
void pbm_param (char *s);
struct image *newimage (int nr, int nc);
void freeimage (struct image *z);
void sys_abort (int val, char *mess);
void CopyVarImage (IMAGE *a, IMAGE *b);
void Display (IMAGE x);
float ** f2d (int nr, int nc);
void srand32 (long k);
double drand32 ();
void copy (IMAGE *a, IMAGE b);

float gauss(float x, float sigma);
float LoG (float x, float sigma);
float meanGauss (float x, float sigma);
void marr (float s, IMAGE im);
void dolap (float **x, int nr, int nc, float **y);
void zero_cross (float **lapim, IMAGE im);
float norm (float x, float y);
float distance (float a, float b, float c, float d);
void convolution (IMAGE im, float **mask, int nr, int nc, float **res,
int NR, int NC);

float norm (float x, float y)
<
return (float) sqrt ( (double)(x*x + y*y) );
>

float distance (float a, float b, float c, float d)
<
return norm ( (a-c), (b-d) );
>

void marr (float s, IMAGE im)
<
int width;
float **smx;
int i,j,k,n;
float **lgau, z;

/* Create a Gaussian and a derivative of Gaussian filter mask */
width = 3.35*s + 0.33;
n = width+width + 1;
printf («Smoothing with a Gaussian of size %dx%dn», n, n);
lgau = f2d (n, n);
for (i=0; i for (j=0; j lgau[i][j] = LoG (distance ((float)i, (float)j,
(float)width, (float)width), s);

/* Convolution of source image with a Gaussian in X and Y directions */
smx = f2d (im->info->nr, im->info->nc);
printf («Convolution with LoG:n»);
convolution (im, lgau, n, n, smx, im->info->nr, im->info->nc);

/* Locate the zero crossings */
printf («Zero crossings:n»);
zero_cross (smx, im);

/* Clear the boundary */
for (i=0; i info->nr; i++)
<
for (j=0; j data[i][j] = 0;
for (j=im->info->nc-width-1; j info->nc; j++)
im->data[i][j] = 0;
>
for (j=0; j info->nc; j++)
<
for (i=0; i data[i][j] = 0;
for (i=im->info->nr-width-1; i info->nr; i++)
im->data[i][j] = 0;
>

free(smx[0]); free(smx);
free(lgau[0]); free(lgau);
>

/* Gaussian */
float gauss(float x, float sigma)
<
return (float)exp((double) ((-x*x)/(2*sigma*sigma)));
>

float meanGauss (float x, float sigma)
<
float z;

z = (gauss(x,sigma)+gauss(x+0.5,sigma)+gauss(x-0.5,sigma))/3.0;
z = z/(PI*2.0*sigma*sigma);
return z;
>

float LoG (float x, float sigma)
<
float x1;

x1 = gauss (x, sigma);
return (x*x-2*sigma*sigma)/(sigma*sigma*sigma*sigma) * x1;
>

void convolution (IMAGE im, float **mask, int nr, int nc, float **res,
int NR, int NC)
<
int i,j,ii,jj, n, m, k, kk;
float x, y;

k = nr/2; kk = nc/2;
for (i=0; i for (j=0; j <
x = 0.0;
for (ii=0; ii <
n = i — k + ii;
if (n =NR) continue;
for (jj=0; jj <
m = j — kk + jj;
if (m =NC) continue;
x += mask[ii][jj] * (float)(im->data[n][m]);
>
>
res[i][j] = x;
>
>

void zero_cross (float **lapim, IMAGE im)
<
int i,j,k,n,m, dx, dy;
float x, y, z;
int xi,xj,yi,yj, count = 0;
IMAGE deriv;

for (i=1; i info->nr-1; i++)
for (j=1; j info->nc-1; j++)
<
im->data[i][j] = 0;
if(lapim[i-1][j]*lapim[i+1][j] data[i][j]=255; continue;>
if(lapim[i][j-1]*lapim[i][j+1] data[i][j]=255; continue;>
if(lapim[i+1][j-1]*lapim[i-1][j+1] data[i][j]=255; continue;>
if(lapim[i-1][j-1]*lapim[i+1][j+1] data[i][j]=255; continue;>
>
>

/* An alternative way to compute a Laplacian */
void dolap (float **x, int nr, int nc, float **y)
<
int i,j,k,n,m;
float u,v;

/* PRINT_SE — Print a structuring element to the screen */
void print_se (IMAGE p)
<
int i,j;

printf («n=====================================================n»);
if (p == NULL)
printf (» Structuring element is NULL.n»);
else
<
printf («Structuring element: %dx%d origin at (%d,%d)n»,
p->info->nr, p->info->nc, p->info->oi, p->info->oj);
for (i=0; i

struct image *newimage (int nr, int nc)
<
struct image *x; /* New image */
int i;
unsigned char *p;

if (nr printf («Error: Bad image size (%d,%d)n», nr, nc);
return 0;
>

/* Allocate the image structure */
x = (struct image *) malloc( sizeof (struct image) );
if (!x) <
printf («Out of storage in NEWIMAGE.n»);
return 0;
>

/* Allocate and initialize the header */

x->info = (struct header *)malloc( sizeof(struct header) );
if (!(x->info))
<
printf («Out of storage in NEWIMAGE.n»);
return 0;
>
x->info->nr = nr; x->info->nc = nc;
x->info->oi = x->info->oj = 0;

/* Allocate the pixel array */

x->data = (unsigned char **)malloc(sizeof(unsigned char *)*nr);

/* Pointers to rows */
if (!(x->data))
<
printf («Out of storage in NEWIMAGE.n»);
return 0;
>

x->data[0] = (unsigned char *)malloc (nr*nc);
p = x->data[0];
if (x->data[0]==0)
<
printf («Out of storage. Newimage n»);
exit(1);
>

void freeimage (struct image *z)
<
/* Free the storage associated with the image Z */

void sys_abort (int val, char *mess)
<
fprintf (stderr, «**** System library ABORT %d: %s ****n»,
val, mess);
exit (2);
>

void copy (IMAGE *a, IMAGE b)
<
CopyVarImage (a, &b);
>

void CopyVarImage (IMAGE *a, IMAGE *b)
<
int i,j;

if (a == b) return;
if (*a) freeimage (*a);
*a = newimage ((*b)->info->nr, (*b)->info->nc);
if (*a == 0) sys_abort (0, «No more storage.n»);

for (i=0; i info->nr; i++)
for (j=0; j info->nc; j++)
(*a)->data[i][j] = (*b)->data[i][j];
(*a)->info->oi = (*b)->info->oi;
(*a)->info->oj = (*b)->info->oj;
>

float ** f2d (int nr, int nc)
<
float **x;
int i;

x = (float **)calloc ( nr, sizeof (float *) );
if (x == 0)
<
fprintf (stderr, «Out of storage: F2D.n»);
exit (1);
>

for (i=0; i <
x[i] = (float *) calloc ( nc, sizeof (float) );
if (x[i] == 0)
<
fprintf (stderr, «Out of storage: F2D %d.n», i);
exit (1);
>
>
return x;
>

void free2d (float **x, int nr)
<
int i;

/* Small system random number generator */
double drand32 ()
<
static long a=16807L, m=2147483647L,
q=127773L, r = 2836L;
long lo, hi, test;

hi = seed / q;
lo = seed % q;
test = a*lo -r*hi;
if (test>0) seed = test;
else seed = test + m;

void srand32 (long k)
<
seed = k;
>

IplImage *toOpenCV (IMAGE x)
<
IplImage *img;
int i=0, j=0;
CvScalar s;

img = cvCreateImage(cvSize(x->info->nc, x->info->nr),8, 1);
for (i=0; i info->nr; i++)
<
for (j=0; j info->nc; j++)
<
s.val[0] = x->data[i][j];
cvSet2D (img, i,j,s);
>
>
return img;
>

for (i=0; i height; i++)
<
for (j=0; j width; j++)
<
s = cvGet2D (x, i, j);
if (color)
k = (unsigned char)((s.val[0] + s.val[1] + s.val[2])/3);
else k = (unsigned char)(s.val[0]);
img->data[i][j] = k;
>
>
return img;
>

/* Display an image on th escreen */
void display_image (IMAGE x)
<
IplImage *image = 0;
char wn[20];
int i;

image = toOpenCV (x);
if (image for (i=0; i wn[19] = ‘’;
cvNamedWindow( wn, CV_WINDOW_AUTOSIZE );
cvShowImage( wn, image );
cvWaitKey(0);
cvReleaseImage( &image );
>

void save_image (IMAGE x, char *name)
<
IplImage *image = 0;

image = toOpenCV (x);
if (image cvSaveImage( name, image );
cvReleaseImage( &image );
>

IMAGE get_image (char *name)
<
IMAGE x=0;
IplImage *image = 0;

image = cvLoadImage(name, 0);
if (image x = fromOpenCV (image);
cvReleaseImage( &image );
return x;
>

IMAGE grab_image ()
<
CvCapture *camera = 0;
IplImage *image = 0;
IMAGE x;

camera = cvCaptureFromCAM( CV_CAP_ANY );
if( !camera ) // Get a camera?
<
fprintf(stderr, «Can initialize cameran»);
return 0;
>
image = cvQueryFrame( camera );
x = fromOpenCV (image);
cvReleaseCapture( &camera );
return x;
>

int get_RGB (IMAGE *r, IMAGE *g, IMAGE *b, char *name)
<
IplImage *image = 0;
IMAGE i1, i2, i3;
int i,j;

// Read the image from a file into Ip1Image
image = cvLoadImage(name, 1);
if (image // Create three AIPCV images of correct size
i1 = newimage (image->height, image->width);
i2 = newimage (image->height, image->width);
i3 = newimage (image->height, image->width);

// Copy pixels from Ip1Image to AIPCV images
for (i=0; i height; i++)
for (j=0; j width; j++)
<
i1->data[i][j] = (image->imageData+i*image->widthStep)[j*image->nChannels+0];
i2->data[i][j] = (image->imageData+i*image->widthStep)[j*image->nChannels+1];
i3->data[i][j] = (image->imageData+i*image->widthStep)[j*image->nChannels+2];
>
cvReleaseImage(&image);
*r = i3;
*g = i2;
*b = i1;
return 1;
>

int save_RGB (IMAGE r, IMAGE g, IMAGE b, char *name)
<
IplImage *image = 0;
int i,j,k;

if ( (r->info->nc != g->info->nc) || (r->info->nr != g->info->nr) ) return 0;
if ( (r->info->nc != b->info->nc) || (r->info->nr != b->info->nr) ) return 0;

// Create an IplImage
image = cvCreateImage(cvSize(r->info->nc, r->info->nr),IPL_DEPTH_8U,3);
if (image // Copy pixels from AIPCV images into Ip1Image
/* for (i=0; i info->nr; i++)
<
for (j=0; j info->nc; j++)
<
s.val[0] = b->data[i][j];
s.val[1] = g->data[i][j];
s.val[2] = r->data[i][j];
cvSet2D (image, i,j,s);
>
> */

for (i=0; i height; i++)
for (j=0; j width; j++)
<
(image->imageData+i*image->widthStep)[j*image->nChannels+0] = b->data[i][j];
(image->imageData+i*image->widthStep)[j*image->nChannels+1] = g->data[i][j];
(image->imageData+i*image->widthStep)[j*image->nChannels+2] = r->data[i][j];
>
k = cvSaveImage(name, image);
cvReleaseImage(&image);
return 1-k;

int main ()
<
int i,j,n;
float s=1.0;
FILE *params;
IMAGE im1, im2;
char name[128];

// Try to read an image
printf («Enter path to the image file to be processed: «);
scanf («%s», name);
printf («Opening file ‘%s’n», name);
im1 = get_image(name);
printf («Enter standard deviation: «);
scanf («%f», &s);

/* Look for parameter file */
im2 = newimage (im1->info->nr, im1->info->nc);
for (i=0; i info->nr; i++)
for (j=0; j info->nc; j++)
im2->data[i][j] = im1->data[i][j];

/* Apply the filter */
marr (s-0.8, im1);
marr (s+0.8, im2);

Источник

0 / 2 / 1

Регистрация: 14.02.2011

Сообщений: 100

1

26.01.2012, 11:37. Показов 3705. Ответов 3


Кто-нибудь использовал MAPI?
Я попытался, вот проблемы:
на включаемый файл mapix.h VC реагирует кучей ошибок
решил проблему так:
[bold]namespace MAPI{[/bold]
#include <mapix.h>
[bold]}//ns
using namespace MAPI;[/bold]

дальше… линкуем mapi32.dll
результат:
Linking…
C:WINDOWSsystem32Mapi32.dll : fatal error LNK1136: invalid or corrupt file

почему?
вообще как нормально использовать MAPI?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



0 / 2 / 1

Регистрация: 14.02.2011

Сообщений: 100

26.01.2012, 12:45

 [ТС]

2

На счёт DLL-ки:
похоже я в свойствах проекта не туда воткнул ссылку на неё.
подскажите куда писать ссылки на дополнительные DLL-ки?



0



7 / 7 / 12

Регистрация: 13.02.2007

Сообщений: 1,255

26.01.2012, 17:58

3

Посмотри вот здесь:
http://www.codeproject.com/internet/cimapi.asp
http://www.codeguru.com/internet/imapi.shtml

Цитата:

«CIMapi internals

The constructor zeroes some internal structures and then attempts to load MAPI32.DLL. If it fails to load the DLL it sets an internal error variable to IMAPI_LOADFAILED and returns. If it succeeds in loading the DLL it searches for the MAPISendMail entry point in the DLL. If it finds this entry point it assumes it has a valid DLL, otherwise it sets the internal error variable to IMAPI_INVALIDDLL and returns.»

Судя по всему библиотеку не линкуют, а подгружают динамически во время работы программы.

Может это как-нибудь тебе поможет.

Удачи,
Владимир



0



0 / 2 / 1

Регистрация: 14.02.2011

Сообщений: 100

27.01.2012, 08:39

 [ТС]

4

boombastik, не, всё гараздо проще. я разобрался.
надо lib-файл линковать. Ну то есть сначала implib.
а mapi32.lib я нашёл.
чем дальше тем больше забываешь элементарные вещи…
а то что ты нашёл это мне ещё наверно пригодится.
Спасибо.



0



Below is my program (marr.cpp).

/* Marr/Hildreth edge detection */

#include «stdafx.h»
#include «stdio.h»
#include «cv.h»
#include «highgui.h»

#define PI 3.1415926535

/* The image header data structure      */
struct header 
{
int nr, nc;             /* Rows and columns in the image */
int oi, oj;             /* Origin */
};

/*      The IMAGE data structure        */
struct image 
{
struct header *info;            /* Pointer to header */
unsigned char **data;           /* Pixel values */
};

#define SQRT2 1.414213562
#define BLACK 0
#define WHITE 1

long seed = 132531;
typedef struct image * IMAGE;

#if defined (MAX)
int    PBM_SE_ORIGIN_COL=0, PBM_SE_ORIGIN_ROW=0;
char **arg;
int maxargs;
#else
extern int PBM_SE_ORIGIN_COL, PBM_SE_ORIGIN_ROW;
#endif

int range (IMAGE im, int i, int j);
void print_se (IMAGE p);
IMAGE Input_PBM (char *fn);
IMAGE Output_PBM (IMAGE image, char *filename);
void get_num_pbm (FILE *f, char *b, int *bi, int *res);
void pbm_getln (FILE *f, char *b);
void pbm_param (char *s);
struct image  *newimage (int nr, int nc);
void freeimage (struct image  *z);
void sys_abort (int val, char *mess);
void CopyVarImage (IMAGE *a, IMAGE *b);
void Display (IMAGE x);
float ** f2d (int nr, int nc);
void srand32 (long k);
double drand32 ();
void copy (IMAGE *a, IMAGE b);

float gauss(float x, float sigma);
float LoG (float x, float sigma);
float meanGauss (float x, float sigma);
void marr (float s, IMAGE im);
void dolap (float **x, int nr, int nc, float **y);
void zero_cross (float **lapim, IMAGE im);
float norm (float x, float y);
float distance (float a, float b, float c, float d);
void convolution (IMAGE im, float **mask, int nr, int nc, float **res,
int NR, int NC);

float norm (float x, float y)
{
return (float) sqrt ( (double)(x*x + y*y) );
}

float distance (float a, float b, float c, float d)
{
return norm ( (a-c), (b-d) );
}

void marr (float s, IMAGE im)
{
int width;
float **smx;
int i,j,k,n;
float **lgau, z;

/* Create a Gaussian and a derivative of Gaussian filter mask  */
width = 3.35*s + 0.33;
n = width+width + 1;
printf («Smoothing with a Gaussian of size %dx%dn», n, n);
lgau = f2d (n, n);
for (i=0; i<n; i++)
 for (j=0; j<n; j++)
   lgau[i][j] = LoG (distance ((float)i, (float)j,
(float)width, (float)width), s);

/* Convolution of source image with a Gaussian in X and Y directions  */
smx = f2d (im->info->nr, im->info->nc);
printf («Convolution with LoG:n»);
convolution (im, lgau, n, n, smx, im->info->nr, im->info->nc);

/* Locate the zero crossings */
printf («Zero crossings:n»);
zero_cross (smx, im);

/* Clear the boundary */
for (i=0; i<im->info->nr; i++)
{
 for (j=0; j<=width; j++) im->data[i][j] = 0;
 for (j=im->info->nc-width-1; j<im->info->nc; j++)
im->data[i][j] = 0;
}
for (j=0; j<im->info->nc; j++)
{
 for (i=0; i<= width; i++) im->data[i][j] = 0;
 for (i=im->info->nr-width-1; i<im->info->nr; i++)
im->data[i][j] = 0;
}

free(smx[0]); free(smx);
free(lgau[0]); free(lgau);
}

/* Gaussian
*/
float gauss(float x, float sigma)
{
    return (float)exp((double) ((-x*x)/(2*sigma*sigma)));
}

float meanGauss (float x, float sigma)
{
float z;

z = (gauss(x,sigma)+gauss(x+0.5,sigma)+gauss(x-0.5,sigma))/3.0;
z = z/(PI*2.0*sigma*sigma);
return z;
}

float LoG (float x, float sigma)
{
float x1;

x1 = gauss (x, sigma);
return (x*x-2*sigma*sigma)/(sigma*sigma*sigma*sigma) * x1;
}

void convolution (IMAGE im, float **mask, int nr, int nc, float **res,
int NR, int NC)
{
int i,j,ii,jj, n, m, k, kk;
float x, y;

k = nr/2; kk = nc/2;
for (i=0; i<NR; i++)
 for (j=0; j<NC; j++)
 {
   x = 0.0;
   for (ii=0; ii<nr; ii++)
   {
     n = i — k + ii;
     if (n<0 || n>=NR) continue;
     for (jj=0; jj<nc; jj++)
     {
m = j — kk + jj;
if (m<0 || m>=NC) continue;
x += mask[ii][jj] * (float)(im->data[n][m]);
     }
   }
   res[i][j] = x;
 }
}

void zero_cross (float **lapim, IMAGE im)
{
int i,j,k,n,m, dx, dy;
float x, y, z;
int xi,xj,yi,yj, count = 0;
IMAGE deriv;

for (i=1; i<im->info->nr-1; i++)
 for (j=1; j<im->info->nc-1; j++)
 {
   im->data[i][j] = 0;
   if(lapim[i-1][j]*lapim[i+1][j]<0) {im->data[i][j]=255; continue;}
   if(lapim[i][j-1]*lapim[i][j+1]<0) {im->data[i][j]=255; continue;}
   if(lapim[i+1][j-1]*lapim[i-1][j+1]<0) {im->data[i][j]=255; continue;}
   if(lapim[i-1][j-1]*lapim[i+1][j+1]<0) {im->data[i][j]=255; continue;}
 }
}

/* An alternative way to compute a Laplacian
*/
void dolap (float **x, int nr, int nc, float **y)
{
int i,j,k,n,m;
float u,v;

for (i=1; i<nr-1; i++)
 for (j=1; j<nc-1; j++)
 {
   y[i][j] = (x[i][j+1]+x[i][j-1]+x[i-1][j]+x[i+1][j]) — 4*x[i][j];
   if (u>y[i][j]) u = y[i][j];
   if (v<y[i][j]) v = y[i][j];
 }
}

/*      PRINT_SE — Print a structuring element to the screen    */
void print_se (IMAGE p)
{
int i,j;

printf («n=====================================================n»);
if (p == NULL)
 printf (» Structuring element is NULL.n»);
else 
{
 printf («Structuring element: %dx%d origin at (%d,%d)n»,
p->info->nr, p->info->nc, p->info->oi, p->info->oj);
 for (i=0; i<p->info->nr; i++)
 {
   printf («
«);
   for (j=0; j<p->info->nc; j++)
     printf («%4d «, p->data[i][j]);
   printf («n»);
 }
}
printf («n=====================================================n»);
}

struct image  *newimage (int nr, int nc)
{
struct image  *x;                /* New image */
int i;
unsigned char *p;

if (nr < 0 || nc < 0) {
printf («Error: Bad image size (%d,%d)n», nr, nc);
return 0;
}

/*      Allocate the image structure    */
x = (struct image  *) malloc( sizeof (struct image) );
if (!x) {
printf («Out of storage in NEWIMAGE.n»);
return 0;
}

/*      Allocate and initialize the header      */

x->info = (struct header *)malloc( sizeof(struct header) );
if (!(x->info)) 
{
printf («Out of storage in NEWIMAGE.n»);
return 0;
}
x->info->nr = nr;       x->info->nc = nc;
x->info->oi = x->info->oj = 0;

/*      Allocate the pixel array        */

x->data = (unsigned char **)malloc(sizeof(unsigned char *)*nr); 

/* Pointers to rows */
if (!(x->data)) 
{
printf («Out of storage in NEWIMAGE.n»);
return 0;
}

x->data[0] = (unsigned char *)malloc (nr*nc);
p = x->data[0];
if (x->data[0]==0)
 {
printf («Out of storage. Newimage  n»);
exit(1);
 }

for (i=1; i<nr; i++) 
{
 x->data[i] = (p+i*nc);
}

return x;
}

void freeimage (struct image  *z)
{
/*      Free the storage associated with the image Z    */

if (z != 0) 
{
  free (z->data[0]);
  free (z->info);
  free (z->data);
  free (z);
}
}

void sys_abort (int val, char *mess)
{
fprintf (stderr, «**** System library ABORT %d: %s ****n», 
val, mess);
exit (2);
}

void copy (IMAGE *a, IMAGE b)
{
CopyVarImage (a, &b);
}

void CopyVarImage (IMAGE *a, IMAGE *b)
{
int i,j;

if (a == b) return;
if (*a) freeimage (*a);
*a = newimage ((*b)->info->nr, (*b)->info->nc);
if (*a == 0) sys_abort (0, «No more storage.n»);

for (i=0; i<(*b)->info->nr; i++)
 for (j=0; j< (*b)->info->nc; j++)
   (*a)->data[i][j] = (*b)->data[i][j];
(*a)->info->oi = (*b)->info->oi;
(*a)->info->oj = (*b)->info->oj;
}

float ** f2d (int nr, int nc)
{
float **x;
int i;

x = (float **)calloc ( nr, sizeof (float *) );
if (x == 0)
{
 fprintf (stderr, «Out of storage: F2D.n»);
 exit (1);
}

for (i=0; i<nr; i++)
{  
 x[i] = (float *) calloc ( nc, sizeof (float)  );
 if (x[i] == 0)
 {
   fprintf (stderr, «Out of storage: F2D %d.n», i);
   exit (1);
 }
}
return x;
}

void free2d (float **x, int nr)
{
int i;

for (i=0; i<nr; i++)
free(x[i]);
free (x);
}

/* Small system random number generator */
double drand32 ()
{
static long a=16807L, m=2147483647L,
   q=127773L, r = 2836L;
long lo, hi, test;

hi = seed / q;
lo = seed % q;
test = a*lo -r*hi;
if (test>0) seed = test;
else seed = test + m;

return (double)seed/(double)m;
}

void srand32 (long k)
{
seed = k;
}

IplImage *toOpenCV (IMAGE x)
{
IplImage *img;
int i=0, j=0;
CvScalar s;

img = cvCreateImage(cvSize(x->info->nc, x->info->nr),8, 1);
for (i=0; i<x->info->nr; i++)
{
for (j=0; j<x->info->nc; j++)
{
s.val[0] = x->data[i][j];
cvSet2D (img, i,j,s);
}
}
return img;
}

IMAGE fromOpenCV (IplImage *x)
{
IMAGE img;
int color=0, i=0;
int k=0, j=0;
CvScalar s;

if ((x->depth==IPL_DEPTH_8U) &&(x->nChannels==1))
// 1 Pixel (grey) image
img = newimage (x->height, x->width);
else if ((x->depth==8) && (x->nChannels==3)) //Color
{
color = 1;
img = newimage (x->height, x->width);
}
else return 0;

for (i=0; i<x->height; i++)
{
for (j=0; j<x->width; j++)
{
s = cvGet2D (x, i, j);
if (color) 
 k = (unsigned char)((s.val[0] + s.val[1] + s.val[2])/3);
else k = (unsigned char)(s.val[0]);
img->data[i][j] = k;
}
}
return img;
}

/* Display an image on th escreen */
void display_image (IMAGE x)
{
IplImage *image = 0;
char wn[20];
int i;

image = toOpenCV (x);
if (image <= 0) return;

for (i=0; i<19; i++) wn[i] = (char)((drand32()*26) + ‘a’);
wn[19] = »;
cvNamedWindow( wn, CV_WINDOW_AUTOSIZE );
cvShowImage( wn, image );
cvWaitKey(0);
cvReleaseImage( &image );
}

void save_image (IMAGE x, char *name)
{
IplImage *image = 0;

image = toOpenCV (x);
if (image <0) return;

cvSaveImage( name, image );
cvReleaseImage( &image );
}

IMAGE get_image (char *name)
{
IMAGE x=0;
IplImage *image = 0;

image = cvLoadImage(name, 0);
if (image <= 0) return 0;
x = fromOpenCV (image);
cvReleaseImage( &image );
return x;
}

IMAGE grab_image ()
{
CvCapture  *camera = 0;
IplImage *image = 0;
IMAGE x;

camera = cvCaptureFromCAM( CV_CAP_ANY );
if( !camera )
// Get a camera?
{
fprintf(stderr, «Can initialize cameran»);
return 0;
}
image = cvQueryFrame( camera );

x = fromOpenCV (image);
cvReleaseCapture( &camera );
return x;
}

int get_RGB (IMAGE *r, IMAGE *g, IMAGE *b, char *name)
{
IplImage *image = 0;
IMAGE i1, i2, i3;
int i,j;

// Read the image from a file into Ip1Image
image = cvLoadImage(name, 1);
if (image <= 0) return 0;

// Create three AIPCV images of correct size
i1 = newimage (image->height, image->width);
i2 = newimage (image->height, image->width);
i3 = newimage (image->height, image->width);

// Copy pixels from Ip1Image to AIPCV images
for (i=0; i<image->height; i++)
for (j=0; j<image->width; j++)
{
 i1->data[i][j] = (image->imageData+i*image->widthStep)[j*image->nChannels+0];
 i2->data[i][j] = (image->imageData+i*image->widthStep)[j*image->nChannels+1];
 i3->data[i][j] = (image->imageData+i*image->widthStep)[j*image->nChannels+2];
}
cvReleaseImage(&image);
*r = i3; 
*g = i2;
*b = i1;
return 1;
}

int save_RGB (IMAGE r, IMAGE g, IMAGE b, char *name)
{
IplImage *image = 0;
int i,j,k;

if ( (r->info->nc != g->info->nc) || (r->info->nr != g->info->nr) ) return 0;
if ( (r->info->nc != b->info->nc) || (r->info->nr != b->info->nr) ) return 0;

// Create an  IplImage
image = cvCreateImage(cvSize(r->info->nc, r->info->nr),IPL_DEPTH_8U,3);
if (image <= 0) return 0;

// Copy pixels from AIPCV images into Ip1Image
/* for (i=0; i<r->info->nr; i++)
{
for (j=0; j<r->info->nc; j++)
{
s.val[0] = b->data[i][j];
s.val[1] = g->data[i][j];
s.val[2] = r->data[i][j];
cvSet2D (image, i,j,s);
}
} */

for (i=0; i<image->height; i++)
for (j=0; j<image->width; j++)
{
 (image->imageData+i*image->widthStep)[j*image->nChannels+0] = b->data[i][j];
 (image->imageData+i*image->widthStep)[j*image->nChannels+1] = g->data[i][j];
 (image->imageData+i*image->widthStep)[j*image->nChannels+2] = r->data[i][j];

k = cvSaveImage(name, image);
cvReleaseImage(&image);
return 1-k;

}

int main ()
{
int i,j,n;
float s=1.0;
FILE *params;
IMAGE im1, im2;
char name[128];

// Try to read an image
printf («Enter path to the image file to be processed: «);
scanf («%s», name);
printf («Opening file ‘%s’n», name);
im1 = get_image(name);
printf («Enter standard deviation: «);
scanf («%f», &s);

display_image (im1);

/* Look for parameter file */
im2 = newimage (im1->info->nr, im1->info->nc);
for (i=0; i<im1->info->nr; i++)
 for (j=0; j<im1->info->nc; j++)
   im2->data[i][j] = im1->data[i][j];

/* Apply the filter */
marr (s-0.8, im1);
marr (s+0.8, im2);

for (i=0; i<im1->info->nr; i++)
 for (j=0; j<im1->info->nc; j++)
   if (im1->data[i][j] > 0 && im2->data[i][j] > 0)
im1->data[i][j] = 0;
   else im1->data[i][j] = 255;

display_image (im1);
save_image (im1, «marr.jpg»);

return 0;
}

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error lnk1120 1 unresolved externals masm
  • Fatal error lnk1113 invalid machine type
  • Fatal error lnk1112 тип компьютера модуля x64 противоречит типу целевого компьютера x86
  • Fatal error lnk1112 module machine type x86 conflicts with target machine type x64
  • Fatal error lnk1107

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии