简体   繁体   中英

Image rotation, falsify image Histograms

I got that function that, by giving it an integer value, it rotate my image (I'm using OpenCV to store that object).

Here's my rotation function code:

float rads = angle*3.1415926/180.0;
float _cos = cos(-rads);
float _sin = sin(-rads);
float xcenter = (float)(src.cols)/2.0;
float ycenter = (float)(src.rows)/2.0;

for(int i = 0; i < src.rows; i++) {
    for(int j = 0; j < src.cols; j++) {
        int x = ycenter + ((float)(i)-ycenter)*_cos - ((float)(j)-xcenter)*_sin;
        int y = xcenter + ((float)(i)-ycenter)*_sin + ((float)(j)-xcenter)*_cos;
        if (x >= 0 && x < src.rows && y >= 0 && y < src.cols) {
            dst.at<cv::Vec3b>(i ,j) = src.at<cv::Vec3b>(x, y);
        } else
            dst.at<cv::Vec3b>(i ,j) = NULL;
    }
}

As you can see, the last line set a NULL value to the 'empty' pixels, and that's the results:

在此输入图像描述

as you can see, the Histogram in the upper right corner, as now I got lots of Black Pixels, is not reliable anymore, as I rotate my image, the histogram should remain like:

在此输入图像描述

here's my code for calculating the 3 Histograms:

int k = 0, r = 255, g = 255, b = 255;
switch (channel){ 
    case 0:
        k = 0; r = 255; g = 0; b = 0;
        break;
    case 1:
        k = 1; r = 0; g = 255; b = 0;
        break;
    case 2:
        k = 2; r = 0; g = 0; b = 255;
        break;
}

int hist[256];
for(int i = 0; i < 255; i++)
    hist[i] = 0;

for(int i = 0; i < img.rows; i++)
    for(int j = 0; j < img.cols; j++)
        hist[(int)img.at<cv::Vec3b>(i,j)[k]]++;

int hist_w = 299;
int hist_h = 69;
int bin_w = cvRound((double) hist_w/256);

cv::Mat histImage(hist_h, hist_w, CV_8UC3, cv::Scalar(50, 50, 50));

int max = hist[0];

for(int i = 1; i < 256; i++)
    if(max < hist[i])
        max = hist[i];

for(int i = 0; i < 255; i++)
        hist[i] = ((double)hist[i]/max)*histImage.rows;

for(int i = 0; i < 255; i++)
    line(histImage, cv::Point(bin_w*(i), hist_h), cv::Point(bin_w*(i), hist_h - hist[i]), cv::Scalar(r,g,b), 1, 8, 0);

return histImage;

does anybody know how can I fix that?

It is a little weird that you consciously add black pixels to the image and complain that this modifies the histogram! Please note that the new histograms are just… right.

This said, you will obtain the histogram of the non-black parts of the image by clearing the 0 bins in the three channels.

If for some reason you want to avoid those black areas without perturbing the initial histogram too much, and option is to fill them with pixels sampled randomly from the initial image. The image will be ugly, but the histogram safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM