// Structure representing the BMP file header
struct bmpFileHeader {
uint32_t fileSize; // Size of the BMP file in bytes
uint16_t reserved1; // Reserved; actual value depends on the application that creates the image
uint16_t reserved2; // Reserved; actual value depends on the application that creates the image
uint32_t bmpOffset; // Offset where the pixel array (bitmap data) can be found
};
// Structure containing DIB header information of a BMP file
struct bmpFileDibInfo {
uint32_t headerSize; // Size of this header
int32_t width; // Bitmap width in pixels
int32_t height; // Bitmap height in pixels
uint16_t planes; // Number of color planes being used
uint16_t bitsPerPixel; // Number of bits per pixel
uint32_t compression; // Compression method being used
uint32_t imageSize; // Size of the raw bitmap data
int32_t xPixelsPerMeter; // Horizontal resolution of the image (pixel per meter)
int32_t yPixelsPerMeter; // Vertical resolution of the image (pixel per meter)
uint32_t colorsUsed; // Number of colors in the color palette
uint32_t importantColors; // Number of important colors used
};
std::vector<std::vector<uint8_t>> palette;
bmpFileHeader header;
bmpFileDibInfo dibInfo;
public:
Bitmap() { } // Default constructor
// Copy constructor
Bitmap(const Bitmap& other) : pixels(other.pixels), isGrayscale(other.isGrayscale), palette(other.palette) { }
~Bitmap() { pixels.clear(); } // Destructor clearing the pixel data
// Method to load a bitmap from a file
void load(std::string);
// Method to write a bitmap to a file
void write(std::string);
// Method to rotate the bitmap image
void rotate(bool clockwise);
// Method to apply a Gaussian filter to the bitmap image
void applyGaussianFilter(const std::vector<std::vector<float>>& kernel, int numThreads);
void applyGaussianFilterThread(const std::vector<std::vector<float>>& kernel, int startY, int endY);
Assistant
};
// Function to generate a Gaussian kernel
std::vector<std::vector > generateGaussianKernel(int size, float sigma) {
std::vector<std::vector > kernel(size, std::vector(size));
float sum = 0.0;
int halfSize = size / 2;
code
// Calculate the Gaussian values for each position in the kernel
for (int x = -halfSize; x <= halfSize; x++) {
for (int y = -halfSize; y <= halfSize; y++) {
float exponent = -(x * x + y * y) / (2 * sigma * sigma);
float value = exp(exponent) / (2 * M_PI * sigma * sigma);
kernel[x + halfSize][y + halfSize] = value;
sum += value;
}
}
// Normalize the kernel to ensure the sum of all values is 1
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
kernel[i][j] /= sum;
}
}
return kernel;
}
// Extract the image name from a full path
std::string getImageName(std::string &imagePath) {
std::string token;
std::istringstream tokenStream(imagePath);
std::string imageName;
if (!file.is_open()) {
std::cerr << "Error: Could not open file " << fileName << std::endl;
exit(1);
}
unsigned char fileType[2];
file.read(reinterpret_cast<char*>(fileType), 2);
if ((fileType[0] != 'B') || (fileType[1] != 'M')) {
std::cerr << "Error: File is not a BMP file" << std::endl;
exit(1);
}
file.read(reinterpret_cast<char*>(&header), sizeof(bmpFileHeader));
file.read(reinterpret_cast<char*>(&dibInfo), sizeof(bmpFileDibInfo));
// Read palette if 8-bit
if (dibInfo.bitsPerPixel == 8) {
palette.resize(256, std::vector<uint8_t>(4));
for (int i = 0; i < 256; ++i) {
file.read(reinterpret_cast<char*>(palette[i].data()), 4);
}
}
// Read any additional important data
int extraDataSize = header.bmpOffset - sizeof(bmpFileHeader) - sizeof(bmpFileDibInfo) - (dibInfo.bitsPerPixel == 8 ? 256 * 4 : 0);
importantData.resize(extraDataSize);
if (extraDataSize > 0) {
file.read(reinterpret_cast<char*>(importantData.data()), extraDataSize);
}
// Seek to pixel data
file.seekg(header.bmpOffset, std::ios::beg);
// Initialize pixels vector
pixels.resize(dibInfo.width, std::vector<uint8_t>(dibInfo.height));
// Calculate padding
int bytesPerPixel = dibInfo.bitsPerPixel / 8;
int padding = (4 - (dibInfo.width * bytesPerPixel) % 4) % 4;
// Read pixel data row by row
for (int x = 0; x < dibInfo.width; x++) { // BMP stores pixels bottom to top
for (int y = 0; y < dibInfo.height; y++) {
uint8_t pixel;
file.read(reinterpret_cast<char*>(&pixel), sizeof(uint8_t));
//std::cout << y << " " << x << " " << pixel << "\n";
pixels[x][y] = pixel;
}
// Skip padding
file.ignore(padding);
}
// Close the file
file.close();
std::cout << "File loaded\n";
// Optional: Validate read operation
if (!file) {
std::cerr << "Error: Failed to read pixel data from file " << fileName << std::endl;
exit(1);
}
}
// Write the BMP image to a file
void Bitmap::write(std::string fileName) {
std::ofstream file(fileName, std::ios::binary);
code
if (!file) {
std::cerr << "Error: Could not open file for writing." << std::endl;
return;
}
file.write("BM", 2);
file.write(reinterpret_cast<char*>(&header), sizeof(bmpFileHeader));
file.write(reinterpret_cast<char*>(&dibInfo), sizeof(bmpFileDibInfo));
//dibInfo.width = pixels[0].size();
//dibInfo.height = pixels.size();
// If 8-bit, write the color palette
if (dibInfo.bitsPerPixel == 8) {
for (int i = 0; i < 256; i++) {
file.put(palette[i][0]); // Blue
file.put(palette[i][1]); // Green
file.put(palette[i][2]); // Red
file.put(palette[i][3]); // Reserved
}
}
for (auto &data : importantData) {
file.write(reinterpret_cast<char*>(&data), sizeof(uint8_t));
}
file.seekp(header.bmpOffset);
// Write pixel data
int bytesPerPixel = dibInfo.bitsPerPixel / 8;
int padding = (4 - (dibInfo.width * bytesPerPixel) % 4) % 4;
for (int x = 0; x < dibInfo.width; x++) {
for (int y = 0; y < dibInfo.height; y++) {
//std::cout << pixels[x][y] << "\n";
file.put(pixels[x][y]);
}
for (int i = 0; i < padding; i++) {
file.put(0);
}
//file.put(row);
}
file.close();
std::vector <std::vector <uint8_t> > rotatedPixels(heigth, std::vector <uint8_t>(width));
for (int32_t x = 0; x < width; x++) {
for (int32_t y = 0; y < heigth; y++) {
if (clockwise) {
rotatedPixels[y][width - x - 1] = pixels[x][y];
} else {
rotatedPixels[heigth - y - 1][x] = pixels[x][y];
}
}
}
dibInfo.width = heigth;
dibInfo.height = width;
pixels = rotatedPixels;
}
int main() {
// Load image
Bitmap image;
image.load("image.bmp");
image.rotate(false);
image.write("output.bmp");
// Print image info
}
The issue of the output.bmp being completely black likely stems from several problems in your BMP handling code. Below are the primary issues and their respective solutions:
Incorrect Pixel Data Ordering
Improper Header Updates After Transformation
Potential Pixel Storage Misalignment
Let's delve into each problem and provide solutions to ensure your BMP handling is correct.
1. Incorrect Pixel Data Ordering
Problem:
BMP files store pixel data row by row, starting from the bottom row to the top row. In your current implementation, you're iterating over the width (x) first and then the height (y), which can lead to incorrect pixel placement.
Solution:
You should iterate over the rows (height) first and then the columns (width). Additionally, because BMP files store pixel data starting from the bottom, you need to read and write the rows in reverse order.
Implementation:
Modify the load Method:
cpp
void Bitmap::load(std::string fileName) {
std::ifstream file(fileName, std::ios::binary);
if (!file.is_open()) {
std::cerr << "Error: Could not open file " << fileName << std::endl;
exit(1);
}
unsigned char fileType[2];
file.read(reinterpret_cast<char*>(fileType), 2);
if ((fileType[0] != 'B') || (fileType[1] != 'M')) {
std::cerr << "Error: File is not a BMP file" << std::endl;
exit(1);
}
file.read(reinterpret_cast<char*>(&header), sizeof(bmpFileHeader));
file.read(reinterpret_cast<char*>(&dibInfo), sizeof(bmpFileDibInfo));
// Read palette if 8-bit
if (dibInfo.bitsPerPixel == 8) {
palette.resize(256, std::vector<uint8_t>(4));
for (int i = 0; i < 256; ++i) {
file.read(reinterpret_cast<char*>(palette[i].data()), 4);
}
}
// Read any additional important data
int extraDataSize = header.bmpOffset - sizeof(bmpFileHeader) - sizeof(bmpFileDibInfo) - (dibInfo.bitsPerPixel == 8 ? 256 * 4 : 0);
importantData.resize(extraDataSize);
if (extraDataSize > 0) {
file.read(reinterpret_cast<char*>(importantData.data()), extraDataSize);
}
// Seek to pixel data
file.seekg(header.bmpOffset, std::ios::beg);
// Initialize pixels vector: [height][width]
pixels.resize(dibInfo.height, std::vector<uint8_t>(dibInfo.width));
// Calculate padding
int bytesPerPixel = dibInfo.bitsPerPixel / 8;
int padding = (4 - (dibInfo.width * bytesPerPixel) % 4) % 4;
// Read pixel data row by row (from bottom to top)
for (int y = dibInfo.height - 1; y >= 0; y--) { // Start from bottom
for (int x = 0; x < dibInfo.width; x++) {
uint8_t pixel;
file.read(reinterpret_cast<char*>(&pixel), sizeof(uint8_t));
pixels[y][x] = pixel;
}
// Skip padding
file.ignore(padding);
}
// Close the file
file.close();
std::cout << "File loaded\n";
// Optional: Validate read operation
if (!file) {
std::cerr << "Error: Failed to read pixel data from file " << fileName << std::endl;
exit(1);
}
}
Modify the write Method:
cpp
void Bitmap::write(std::string fileName) {
std::ofstream file(fileName, std::ios::binary);
if (!file) {
std::cerr << "Error: Could not open file for writing." << std::endl;
return;
}
// Update header fields before writing
int bytesPerPixel = dibInfo.bitsPerPixel / 8;
int padding = (4 - (dibInfo.width * bytesPerPixel) % 4) % 4;
dibInfo.imageSize = (bytesPerPixel * dibInfo.width + padding) * dibInfo.height;
header.fileSize = header.bmpOffset + dibInfo.imageSize;
// Write headers
file.write("BM", 2);
file.write(reinterpret_cast<char*>(&header), sizeof(bmpFileHeader));
file.write(reinterpret_cast<char*>(&dibInfo), sizeof(bmpFileDibInfo));
// Write palette if 8-bit
if (dibInfo.bitsPerPixel == 8) {
for (int i = 0; i < 256; i++) {
file.put(palette[i][0]); // Blue
file.put(palette[i][1]); // Green
file.put(palette[i][2]); // Red
file.put(palette[i][3]); // Reserved
}
}
// Write any important data
for (auto &data : importantData) {
file.write(reinterpret_cast<char*>(&data), sizeof(uint8_t));
}
// Seek to the pixel data offset
file.seekp(header.bmpOffset, std::ios::beg);
// Write pixel data row by row (from bottom to top)
for (int y = dibInfo.height - 1; y >= 0; y--) { // Start from bottom
for (int x = 0; x < dibInfo.width; x++) {
file.put(pixels[y][x]);
}
// Write padding
for (int i = 0; i < padding; i++) {
file.put(0);
}
}
file.close();
std::cout << "File written successfully.\n";
}
2. Improper Header Updates After Transformation
Problem:
When performing transformations like rotation, the dimensions of the image (width and height) change. However, the related header fields such as fileSize and imageSize are not updated accordingly. This discrepancy can lead to an invalid BMP file structure, causing the image to appear black or corrupted.
Solution:
After any transformation that alters the image dimensions, you must update the BMP header fields to reflect the new image size and file size.
Implementation:
Update Headers in the write Method:
As shown in the modified write method above, before writing the headers, calculate the new imageSize and fileSize based on the current image dimensions and bits per pixel.
Ensure that these calculations are accurate based on the current state of the image.
3. Potential Pixel Storage Misalignment
Problem:
In the initial code, the pixel data is stored as pixels[x][y], which can lead to confusion and misalignment since images are typically handled as pixels[y][x] where y represents rows and x represents columns.
Solution:
To maintain clarity and avoid misalignment, store pixel data as pixels[y][x] where each y corresponds to a row and each x corresponds to a column within that row.
Implementation:
Adjust Pixel Storage:
Ensure that both loading and writing processes treat the first index as the row (y) and the second index as the column (x).
cpp
// Example: Initializing pixel storage
pixels.resize(dibInfo.height, std::vector<uint8_t>(dibInfo.width));
// Loading pixels
for (int y = dibInfo.height - 1; y >= 0; y--) { // Start from bottom
for (int x = 0; x < dibInfo.width; x++) {
uint8_t pixel;
file.read(reinterpret_cast<char*>(&pixel), sizeof(uint8_t));
pixels[y][x] = pixel;
}
file.ignore(padding);
}
// Writing pixels
for (int y = dibInfo.height - 1; y >= 0; y--) { // Start from bottom
for (int x = 0; x < dibInfo.width; x++) {
file.put(pixels[y][x]);
}
for (int i = 0; i < padding; i++) {
file.put(0);
}
}
Modify the rotate Method Accordingly:
Ensure that the rotation logic correctly interprets pixels[y][x].
cpp
void Bitmap::rotate(bool clockwise) {
int32_t originalWidth = dibInfo.width;
int32_t originalHeight = dibInfo.height;
std::vector<std::vector<uint8_t>> rotatedPixels(originalWidth, std::vector<uint8_t>(originalHeight));
for (int y = 0; y < originalHeight; y++) {
for (int x = 0; x < originalWidth; x++) {
if (clockwise) {
rotatedPixels[x][originalHeight - y - 1] = pixels[y][x];
} else {
rotatedPixels[originalWidth - x - 1][y] = pixels[y][x];
}
}
}
// Update dimensions
dibInfo.width = originalHeight;
dibInfo.height = originalWidth;
// Replace pixel data
pixels = rotatedPixels;
}
Final Code with Corrections Applied
Below is the revised version of your code incorporating all the corrections mentioned above:
cpp
Additional Recommendations
Error Handling:
Always verify that the BMP file you are working with is in a supported format (e.g., 8-bit vs. 24-bit).
Implement more robust error handling to catch and report different types of failures.
Support for Different Bit Depths:
Currently, the code primarily handles 8-bit grayscale images. Consider extending support for 24-bit or other common BMP formats.
Optimizing Pixel Storage:
Depending on your use case, you might benefit from optimizing how you store and manipulate pixel data, potentially using more efficient data structures or libraries.
Use Existing Libraries:
For complex image processing tasks, consider using established libraries like OpenCV which provide optimized and tested functions for image manipulation.
Unit Testing:
Implement unit tests to verify that each component of your BMP handling (loading, writing, rotating) works correctly with various BMP files.
By addressing the pixel ordering, updating header information correctly after transformations, and ensuring proper pixel storage alignment, your BMP read and write operations should function as expected, producing a valid output.bmp that reflects the desired transformations.
#include <cstdint>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <cmath>
#include <unistd.h>
#include <thread>
// Structure representing the BMP file header
#pragma pack(push, 1)
struct bmpFileHeader {
uint16_t bfType; // Signature "BM"
uint32_t fileSize; // Size of the BMP file in bytes
uint16_t reserved1; // Reserved; must be zero
uint16_t reserved2; // Reserved; must be zero
uint32_t bmpOffset; // Offset where the pixel array (bitmap data) can be found
};
// Structure containing DIB header information of a BMP file
struct bmpFileDibInfo {
uint32_t headerSize; // Size of this header
int32_t width; // Bitmap width in pixels
int32_t height; // Bitmap height in pixels
uint16_t planes; // Number of color planes being used
uint16_t bitsPerPixel; // Number of bits per pixel
uint32_t compression; // Compression method being used
uint32_t imageSize; // Size of the raw bitmap data
int32_t xPixelsPerMeter; // Horizontal resolution of the image (pixel per meter)
int32_t yPixelsPerMeter; // Vertical resolution of the image (pixel per meter)
uint32_t colorsUsed; // Number of colors in the color palette
uint32_t importantColors; // Number of important colors used
};
#pragma pack(pop)
// Class representing a Bitmap image
class Bitmap {
private:
bool isGrayscale;
uint8_t bitsPerPixel;
std::vector<std::vector<uint8_t>> pixels; // Stored as [height][width]
std::vector<uint8_t> importantData;
std::vector<std::vector<uint8_t>> palette;
bmpFileHeader header;
bmpFileDibInfo dibInfo;
public:
Bitmap() { } // Default constructor
// Copy constructor
Bitmap(const Bitmap& other) : pixels(other.pixels), isGrayscale(other.isGrayscale), palette(other.palette), header(other.header), dibInfo(other.dibInfo) { }
~Bitmap() { pixels.clear(); } // Destructor clearing the pixel data
// Method to load a bitmap from a file
void load(std::string);
// Method to write a bitmap to a file
void write(std::string);
// Method to rotate the bitmap image
void rotate(bool clockwise);
// Method to apply a Gaussian filter to the bitmap image
void applyGaussianFilter(const std::vector<std::vector<float>>& kernel, int numThreads);
void applyGaussianFilterThread(const std::vector<std::vector<float>>& kernel, int startY, int endY);
};
// Function to generate a Gaussian kernel
std::vector<std::vector<float> > generateGaussianKernel(int size, float sigma) {
std::vector<std::vector<float> > kernel(size, std::vector<float>(size));
float sum = 0.0;
int halfSize = size / 2;
// Calculate the Gaussian values for each position in the kernel
for (int x = -halfSize; x <= halfSize; x++) {
for (int y = -halfSize; y <= halfSize; y++) {
float exponent = -(x * x + y * y) / (2 * sigma * sigma);
float value = exp(exponent) / (2 * M_PI * sigma * sigma);
kernel[x + halfSize][y + halfSize] = value;
sum += value;
}
}
// Normalize the kernel to ensure the sum of all values is 1
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
kernel[i][j] /= sum;
}
}
return kernel;
}
// Extract the image name from a full path
std::string getImageName(std::string &imagePath) {
std::string token;
std::istringstream tokenStream(imagePath);
std::string imageName;
while (std::getline(tokenStream, token, '/')) {
imageName = token;
}
return imageName;
}
void Bitmap::load(std::string fileName) {
std::ifstream file(fileName, std::ios::binary);
if (!file.is_open()) {
std::cerr << "Error: Could not open file " << fileName << std::endl;
exit(1);
}
// Read the file header
file.read(reinterpret_cast<char*>(&header), sizeof(bmpFileHeader));
if (header.bfType != 0x4D42) { // 'BM' in little endian
std::cerr << "Error: File is not a BMP file" << std::endl;
exit(1);
}
// Read the DIB header
file.read(reinterpret_cast<char*>(&dibInfo), sizeof(bmpFileDibInfo));
// Read palette if 8-bit
if (dibInfo.bitsPerPixel == 8) {
palette.resize(256, std::vector<uint8_t>(4));
for (int i = 0; i < 256; ++i) {
file.read(reinterpret_cast<char*>(palette[i].data()), 4);
}
}
// Read any additional important data
int extraDataSize = header.bmpOffset - sizeof(bmpFileHeader) - sizeof(bmpFileDibInfo) - (dibInfo.bitsPerPixel == 8 ? 256 * 4 : 0);
importantData.resize(extraDataSize);
if (extraDataSize > 0) {
file.read(reinterpret_cast<char*>(importantData.data()), extraDataSize);
}
// Seek to pixel data
file.seekg(header.bmpOffset, std::ios::beg);
// Initialize pixels vector: [height][width]
pixels.resize(dibInfo.height, std::vector<uint8_t>(dibInfo.width, 0));
// Calculate padding
int bytesPerPixel = dibInfo.bitsPerPixel / 8;
int padding = (4 - (dibInfo.width * bytesPerPixel) % 4) % 4;
// Read pixel data row by row (from bottom to top)
for (int y = dibInfo.height - 1; y >= 0; y--) { // Start from bottom
for (int x = 0; x < dibInfo.width; x++) {
uint8_t pixel;
file.read(reinterpret_cast<char*>(&pixel), sizeof(uint8_t));
pixels[y][x] = pixel;
}
// Skip padding
file.ignore(padding);
}
// Close the file
file.close();
std::cout << "File loaded\n";
// Optional: Validate read operation
if (!file) {
std::cerr << "Error: Failed to read pixel data from file " << fileName << std::endl;
exit(1);
}
}
// Write the BMP image to a file
void Bitmap::write(std::string fileName) {
std::ofstream file(fileName, std::ios::binary);
if (!file) {
std::cerr << "Error: Could not open file for writing." << std::endl;
return;
}
// Update header fields before writing
int bytesPerPixel = dibInfo.bitsPerPixel / 8;
int padding = (4 - (dibInfo.width * bytesPerPixel) % 4) % 4;
dibInfo.imageSize = (bytesPerPixel * dibInfo.width + padding) * dibInfo.height;
header.fileSize = header.bmpOffset + dibInfo.imageSize;
// Write headers
file.write(reinterpret_cast<char*>(&header), sizeof(bmpFileHeader));
file.write(reinterpret_cast<char*>(&dibInfo), sizeof(bmpFileDibInfo));
// Write palette if 8-bit
if (dibInfo.bitsPerPixel == 8) {
for (int i = 0; i < 256; i++) {
file.put(palette[i][0]); // Blue
file.put(palette[i][1]); // Green
file.put(palette[i][2]); // Red
file.put(palette[i][3]); // Reserved
}
}
// Write any important data
for (auto &data : importantData) {
file.write(reinterpret_cast<char*>(&data), sizeof(uint8_t));
}
// Seek to the pixel data offset
file.seekp(header.bmpOffset, std::ios::beg);
// Write pixel data row by row (from bottom to top)
for (int y = dibInfo.height - 1; y >= 0; y--) { // Start from bottom
for (int x = 0; x < dibInfo.width; x++) {
file.put(pixels[y][x]);
}
// Write padding
for (int i = 0; i < padding; i++) {
file.put(0);
}
}
file.close();
std::cout << "File written successfully.\n";
}
void Bitmap::rotate(bool clockwise) {
int32_t originalWidth = dibInfo.width;
int32_t originalHeight = dibInfo.height;
std::vector<std::vector<uint8_t>> rotatedPixels(originalWidth, std::vector<uint8_t>(originalHeight, 0));
for (int y = 0; y < originalHeight; y++) {
for (int x = 0; x < originalWidth; x++) {
if (clockwise) {
rotatedPixels[x][originalHeight - y - 1] = pixels[y][x];
} else {
rotatedPixels[originalWidth - x - 1][y] = pixels[y][x];
}
}
}
// Update dimensions
dibInfo.width = originalHeight;
dibInfo.height = originalWidth;
// Replace pixel data
pixels = rotatedPixels;
}
int main() {
// Load image
Bitmap image;
image.load("image.bmp");
image.rotate(false);
image.write("output.bmp");
// Print image info
}