Не могу связать libtiff
Я пытаюсь построить программу на C++ с использованием Microsoft Visual Studio 2017.
#include "stdafx.h"
#include <opencv2/core/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
extern "C" {
#include "libtiff/libtiff/tiffio.h"
}
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
string imageName("410.tif"); // start with a default
// If there is an argument, read it in as the name of the image
if (argc > 1)
{
imageName = argv[1];
}
// Open the TIFF file using libtiff
TIFF* tif = TIFFOpen(imageName.c_str(), "r");
// Create a matrix to hold the tif image in
Mat image;
// check the tif is open
if (tif) {
do {
unsigned int width, height;
uint32* raster;
// get the size of the tiff
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
uint npixels = width * height; // get the total number of pixels
raster = (uint32*)_TIFFmalloc(npixels * sizeof(uint32)); // allocate temp memory (must use the tiff library malloc)
if (raster == NULL) // check the raster's memory was allocaed
{
TIFFClose(tif);
cerr << "Could not allocate memory for raster of TIFF image" << endl;
return -1;
}
// Check the tif read to the raster correctly
if (!TIFFReadRGBAImage(tif, width, height, raster, 0))
{
TIFFClose(tif);
cerr << "Could not read raster of TIFF image" << endl;
return -1;
}
image = Mat(width, height, CV_8UC4); // create a new matrix of w x h with 8 bits per channel and 4 channels (RGBA)
// itterate through all the pixels of the tif
for (uint x = 0; x < width; x++)
for (uint y = 0; y < height; y++)
{
uint32& TiffPixel = raster[y*width + x]; // read the current pixel of the TIF
Vec4b& pixel = image.at<Vec4b>(Point(y, x)); // read the current pixel of the matrix
pixel[0] = TIFFGetB(TiffPixel); // Set the pixel values as BGRA
pixel[1] = TIFFGetG(TiffPixel);
pixel[2] = TIFFGetR(TiffPixel);
pixel[3] = TIFFGetA(TiffPixel);
}
_TIFFfree(raster); // release temp memory
// Rotate the image 90 degrees couter clockwise
image = image.t();
flip(image, image, 0);
imshow("TIF Image", image); // show the image
waitKey(0); // wait for anykey before displaying next
} while (TIFFReadDirectory(tif)); // get the next tif
TIFFClose(tif); // close the tif file
}
return 0;
}
Как видите, я включаю libtiff, но когда я пытаюсь скомпилировать, я получаю следующую ошибку:
LNK2019 ссылка на внешний символ _TIFFmalloc не разрешена в функции
Ошибка расширена до "_TIFFfree,TIFFClose, TIFFGetField, TIFFReadDirectory, TIFFReadRGBAImage, TIFFOpen" (я разместил только один, чтобы было проще).
Я попытался найти в Google эту проблему, и я думаю, что это связано с проблемой линковки. Многие люди говорили, что я должен добавить "libtiff.lib" в раздел "input" свойств проекта Visual Studio, но у меня нет libtiff.lib в библиотеке, которую я скачал из официального источника.
Я использую версию библиотеки 4.0.4.
2 ответа
TIFF - это библиотека C, в то время как ваша программа находится на C++, C++ и C имеют различные связывающие ABI.
Когда вы используете библиотеку C из исходного кода C++, вы обычно должны делать что-то вроде:
extern "C" {
#include "libtiff/libtiff/tiffio.h"
}
... сигнализировать C++, что эти символы следуют за C ABI.
ПРИМЕЧАНИЕ. Многие широко используемые библиотеки C включают в свои заголовки условные проверки препроцессора C++, чтобы избежать этой проблемы, например:
#ifdef __cplusplus
extern "C" {
#endif
/* Actual header content */
extern int do_something(void);
extern int do_something_else(const char*);
/* ... */
#ifdef __cplusplus
}
#end
Это не относится к либтифу.
Используя следующую библиотеку: http://gnuwin32.sourceforge.net/packages/tiff.htm Я могу правильно включить libtiff, но проблема в том, что эта библиотека 64-битная, а openCV 32-битная. Итак, я получаю следующую ошибку:
LNK4272 тип библиотечного компьютера "x86" конфликтует с типом целевого компьютера "x64" ImageManipulation C: \ Program Files (x86) \ GnuWin32 \ lib \ libtiff.lib 1
Решение платформы в Visual Studio установлено на x64, потому что, если я включу его, x86, openCV не будет работать.