Приложение для сшивания изображений BMP вместе. Нужна помощь - PullRequest
0 голосов
/ 13 апреля 2019

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

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

Основой файла bmp.h является эта страница: https://solarianprogrammer.com/2018/11/19/cpp-reading-writing-bmp-images/ Я прилагаю свой код и снимок экрана с исключениями, которые выбрасывает VS.

главный:

#include "bmp.h"
#include <fstream>
#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {    

    int totalImages = 0;
    int width = 0;
    int height;
    int count = 0;
    std::string path = "imagini";
    //Here i count the total number of images in the directory. 
    //I need this to know the width of the composed image that i have to produce.
    for (const auto & entry : fs::directory_iterator(path))
        totalImages++;
    //Here i thought about going through the directory and finding out the width of the images inside it.
    //I haven't managed to think of a better way to do this (which is probably why it doesn't work, i guess).
    //Ideally, i would have taken one image from the directory and multiply it's width 
    //by the total number of images in the said directory, thus getting the width of the resulting image i need.
    for (auto& p : fs::directory_iterator(path))
    {
        std::string s = p.path().string();
        const char* imageName = s.c_str();  
        BMP image(imageName);
        width = width + image.bmp_info_header.width;
        height = image.bmp_info_header.height;      
    }

    BMP finalImage(width, height);
    //Finally, I was going to pass the directory again, and for each image inside of it, i would call
    //the create_data function that i wrote in bmp.h.
    for (auto& p : fs::directory_iterator(path))
    {   
        count++;
        std::string s = p.path().string();
        const char* imageName = s.c_str();
        BMP image(imageName);
        //I use count to point out which image the iterator is currently at.
        finalImage.create_data(count, image, totalImages);
    }   
    //Here i would write the finalImage to a bmp image.
    finalImage.write("textura.bmp");
}

bmp.h (я добавил только ту часть, которую написал, остальная часть кода находится по ссылке, указанной выше):

// This is where I try to copy the pixel RGBA values from the image passed as parameter (from it's data vector) to my 
    // resulting image (it's data vector) .
    // The math should be right, I've gone through it with pen&paper, but right now I can't test it because the code doesn't work for other reasons.
    void create_data(int count, BMP image, int totalImages)
    {
        int w = image.bmp_info_header.width * 4;
        int h = image.bmp_info_header.height;
        int q = 0;
        int channels = image.bmp_info_header.bit_count / 8;
        int startJ = w * channels * (count - 1);
        int finalI = w * channels * totalImages* (h - 1);
        int incrementI = w * channels * totalImages;
        for(int i = 0; i <= finalI; i+incrementI)
            for (int j = i + startJ; j < i + startJ + w * channels; j+4) 
            {
                data[j]  =image.data[q];
                data[j+1]=image.data[q+1];
                data[j+2]=image.data[q+2];
                data[j+3]=image.data[q+3];
                q = q + 4;
            }
    }   

Ошибка, которую я получаю: https://imgur.com/7fq9BH4

Это первый раз, когда я отправляю вопрос, я только посмотрел здесь ответы. Если я не предоставил достаточно информации по моей проблеме, или что-то, что я сделал, не в порядке, я прошу прощения.

Кроме того, английский является моим вторым языком, поэтому я надеюсь, что я получил достаточно четкие оценки.

РЕДАКТИРОВАТЬ: Поскольку я забыл упомянуть, я хотел бы сделать этот код без использования внешних библиотек, таких как OpenCV или ImageMagick.

...