How to evenly distribute numbers 0 to n into m different containers - c++

I am trying to write an algorithm for a program to draw an even, vertical gradient across an image. I.e. I want change the pixel color from 0 to 255 along the m rows of an image, but cannot find a good generic algorithm to do so.
I've tried to implement something like this using opencv, but it does not seem to work
#include <opencv2/opencv.hpp>
int main(){
//Make the image white.
cv::Mat Img(w_height, w_width, CV_8U);
for (int y = 0; y < Img.rows; y += 1) {
for (int x = 0; x < Img.cols; x++) {
Img.at<uchar>(y, x) = 255;//White
}
}
// try to create an even, vertical gradient
for(int row = 0; row < Img.rows; row++ ){
for(int col = 0; col < Img.cols; col++){
Img.at<uchar>(row, col) = col % 256;
}
}
cv::imshow("Window", Img);
cv::waitKey(0);
return 0;
}

Solving this problem requires the knowledge of three simple tricks:
1. Interpolation:
The process of gradually changing from one value to another is called interpolation. There are multiple ways of interpolating color values: the simplest one is to interpolate each component linearly, i.e. in the form of:
interpolated = start * (1-t) + dest * t.
Where
start is the value you are interpolating from towards the value dest.
t denotes how close the interpolated value should be to the destination value dest on a scale of 0 to 1 with 0 being the pure start color and 1 being the pure dest color.
You will find that linear interpolation in the RGB color space doesn't produce natural color paths. As an advanced step, you could utilise the HSV color space instead. See this question for further information about color interpolation.
2. Discretisation:
Unfortunately, interpolation produces real numbers. Thus, we have to discretise them to be able to use them as integer color values. The best way to do this is to round to the nearest integer by using e.g. round() in C++.
3. Finding the interpolation point:
Now, we just need a real-valued interpolation point t at each row of our image. We can deduce a formula for this by analysing what output we want to see:
For the bottommost row (row 1) we want to have t == 0 since that is where we want our pure start color to appear.
For the topmost row (row m) we want to have t == 1 since that is where we want the pure destination color to appear.
For every other row we want t to scale linearly with the distance to the bottommost row.
A formula to achieve this result is:
t = rowIndex / m
The approach can readily be adapted to other gradient directions by changing this formula appropriately.
Sample code (using linear interpolation, C++):
#include <algorithm>
#include <cmath>
Color interpolateRGB(Color from, Color to, float t)
{
// Clamp __t__ to range [0,1]
t = std::max(std::min(0.f, t), 1.f);
// Interpolate each RGB component
uint8_t r = std::roundf(from.r * (1-t) + to.r * t);
uint8_t g = std::roundf(from.g * (1-t) + to.g * t);
uint8_t b = std::roundf(from.b * (1-t) + to.b * t);
return Color(r, g, b);
}
void fillWithGradient(Image& img, Color from, Color to)
{
for(size_t row = 0; row < img.numRows(); ++row)
{
Color value = interpolateRGB(from, to, row / (img.numRows()-1));
// Set all pixels of this row to __value__
for(size_t col = 0; col < img.numCols(); ++col)
{
img.setPixel(row, col, value);
}
}
}

The basic idea would be to use the remainder of the division r of n/(m-1) and adding it to n on each iteration:
#include <iostream>
#include <vector>
using namespace std;
vector<int> gradient( int n, int m ) {
div_t q { 0, 0 };
vector<int> grad(m);
for( int i=1 ; i<m ; ++i ) {
q = div( n + q.rem, m-1 );
grad[i] = grad[i-1] + q.quot;
}
return grad;
}
int main() {
for( int i : gradient(255,10) ) cout << i << ' ';
cout << '\n';
return 0;
}
Output:
0 28 56 85 113 141 170 198 226 255

Related

Fast method to access random image pixels and at most once

I'm learning OpenCV (C++) and as a simple practice, I designed a simple effect which makes some of image pixels black or white. I want each pixel to be edited at most once; so I added address of all pixels to a vector. But it made my code very slow; specially for large images or high amounts of effect. Here is my code:
void effect1(Mat& img, float amount) // 100 ≥ amount ≥ 0
{
vector<uchar*> addresses;
int channels = img.channels();
uchar* lastAddress = img.ptr<uchar>(0) + img.total() * channels;
for (uchar* i = img.ptr<uchar>(0); i < lastAddress; i += channels) addresses.push_back(i); //Fast Enough
size_t count = img.total() * amount / 100 / 2;
for (size_t i = 0; i < count; i++)
{
size_t addressIndex = xor128() % addresses.size(); //Fast Enough, xor128() is a fast random number generator
for (size_t j = 0; j < channels; j++)
{
*(addresses[addressIndex] + j) = 255;
} //Fast Enough
addresses.erase(addresses.begin() + addressIndex); // MAKES CODE EXTREMELY SLOW
}
for (size_t i = 0; i < count; i++)
{
size_t addressIndex = xor128() % addresses.size(); //Fast Enough, xor128() is a fast random number generator
for (size_t j = 0; j < channels; j++)
{
*(addresses[addressIndex] + j) = 0;
} //Fast Enough
addresses.erase(addresses.begin() + addressIndex); // MAKES CODE EXTREMELY SLOW
}
}
I think rearranging vector items after erasing an item is what makes my code slow (if I remove addresses.erase, code will run fast).
Is there any fast method to select each random item from a collection (or a number range) at most once?
Also: I'm pretty sure such effect already exists. Does anyone know the name of it?
This answer assumes you have a random bit generator function, since std::random_shuffle requires that. I don't know how xor128 works, so I'll use the functionality of the <random> library.
If we have a population of N items, and we want to select groups of size j and k randomly from that population with no overlap, we can write down the index of each item on a card, shuffle the deck, draw j cards, and then draw k cards. Everything left over is discarded. We can achieve this with the <random> library. Answer pending on how to incorporate a custom PRNG like you implemented with xor128.
This assumes that random_device won't work on your system (many compilers implement it in a way that it will always return the same sequence) so we seed the random generator with current time like the good old fashioned srand our mother used to make.
Untested since I don't know how to use OpenCV. Anyone with a lick of experience with that please edit as appropriate.
#include <ctime> // for std::time
#include <numeric> // for std::iota
#include <random>
#include <vector>
void effect1(Mat& img, float amount, std::mt19937 g) // 0.0 ≥ amount ≥ 1.00
{
std::vector<cv::Size> ind(img.total());
std::iota(ind.begin(), ind.end(), 0); // fills with 0, 1, 2, ...
std::random_shuffle(ind.begin(), ind.end(), g);
cv::Size count = img.total() * amount;
auto white = get_white<Mat>(); // template function to return this matrix' concept of white
// could easily replace with cv::Vec3d(255,255,255)
// if all your matrices are 3 channel?
auto black = get_black<Mat>(); // same but... opposite
auto end = ind.begin() + count;
for (auto it = ind.begin(), it != end; ++it)
{
img.at(*it) = white;
}
end = (ind.begin() + 2 * count) > ind.end() ?
ind.end() :
ind.begin() + 2 * count;
for (auto it = ind.begin() + count; it != end; ++it)
{
img.at(*it) = black;
}
}
int main()
{
std::mt19937 g(std::time(nullptr)); // you normally see this seeded with random_device
// but that's broken on some implementations
// adjust as necessary for your needs
cv::Mat mat = ... // make your cv objects
effect1(mat, 0.1, g);
// display it here
}
Another approach
Instead of shuffling indices and drawing cards from a deck, assume each pixel has a random probability of switching to white, switching to black, or staying the same. If your amount is 0.4, then select a random number between 0.0 and 1.0, any result between 0.0 and 0.4 flips the pixel black, and betwen 0.4 and 0.8 flips it white, otherwise it stays the same.
General algorithm:
given probability of flipping -> f
for each pixel in image -> p:
get next random float([0.0, 1.0)) -> r
if r < f
then p <- BLACK
else if r < 2*f
then p <- WHITE
You won't get the same number of white/black pixels each time, but that's randomness! We're generating a random number for each pixel anyway for the shuffling algorithm. This has the same complexity unless I'm mistaken.
Also: I'm pretty sure such effect already exists. Does anyone know the name of it?
The effect you're describing is called salt and pepper noise. There is no direct implementation in OpenCV that I know of though.
I think rearranging vector items after erasing an item is what makes
my code slow (if I remove addresses.erase, code will run fast).
Im not sure why you add your pixels to a vector in your code, it would make much more sense and also be much more performant to directly work on the Mat object and change the pixel value directly. You could use OpenCVs inbuild Mat.at() function to directly change the pixel values to either 0 or 255.
I would create a single loop which generates random indexes in the range of your image dimension and manipulate the image pixels directly. That way you are in O(n) for your noise addition. You could also just search for "OpenCV" and "salt and pepper noise", I am sure there already are a lot of really performant implementations.
I also post a simpler code:
void saltAndPepper(Mat& img, float amount)
{
vector<size_t> pixels(img.total()); // size_t = unsigned long long
uchar channels = img.channels();
iota(pixels.begin(), pixels.end(), 0); // Fill vector with 0, 1, 2, ...
shuffle(pixels.begin(), pixels.end(), mt19937(time(nullptr))); // Shuffle the vector
size_t count = img.total() * amount / 100 / 2;
for (size_t i = 0; i < count; i++)
{
for (size_t j = 0; j < channels; j++) // Set all pixel channels (e.g. Grayscale with 1 channel or BGR with 3 channels) to 255
{
*(img.ptr<uchar>(0) + (pixels[i] * channels) + j) = 255;
}
}
for (size_t i = count; i < count*2; i++)
{
for (size_t j = 0; j < channels; j++) // Set all pixel channels (e.g. Grayscale with 1 channel or BGR with 3 channels) to 0
{
*(img.ptr<uchar>(0) + (pixels[i] * channels) + j) = 0;
}
}
}

How to reassign an individual element of a 2D parallel vector with a 1D vector?

Hi I am working on an assignment for my introduction to C++ class and I am completely stumped on a certain part. Basically the assignment is to open a file that contains individual integers (the data represents a grid of elevation averages), populate a 2D vector with those values, find the min and max value of the vector, convert each element of the vector to a 1D parallel vector containing the RGB representation of that value (in Grey scale), and export the data as a PPM file. I have successfully reached the point where I am supposed to convert the values of the vector to the RGB parallel vectors.
My issue is that I am not entirely sure how to assign the new RGB vector to the original element of the vector. Here is the code I have currently:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main () {
// initialize inputs
int rows;
int columns;
string fname;
// input options
cout << "Enter number of rows" << endl;
cin >> rows;
cout << "Enter number of columns" << endl;
cin >> columns;
cout << "Enter file name to load" << endl;
cin >> fname;
ifstream inputFS(fname);
// initialize variables
int variableIndex;
vector<vector<int>> dataVector (rows, vector<int> (columns));
int minVal = 0;
int maxVal = 0;
// if file is open, populate vector with data from file
if(inputFS.is_open()) {
for (int i = 0; i < dataVector.size(); i++) {
for (int j = 0; j < dataVector.at(0).size(); j++) {
inputFS >> variableIndex;
dataVector.at(i).at(j) = variableIndex;
}
}
}
// find max and min value within data set
for (int i = 0; i < dataVector.size(); i++) {
for (int j = 0; j < dataVector.at(0).size(); j++) {
if (dataVector.at(i).at(j) < minVal) {
minVal = dataVector.at(i).at(j);
}
if (dataVector.at(i).at(j) > minVal) {
maxVal = dataVector.at(i).at(j);
}
}
}
// initialize variables and new color vector
// -------PART I NEED HELP ON-----------
int range = maxVal - minVal;
int remainderCheck = 0;
double color = 0;
vector<int> colorVector = 3;
for (int i = 0; i < dataVector.size(); i++) {
for (int j = 0; j < dataVector.at(0).size(); j++) {
remainderCheck = dataVector.at(i).at(j) - minVal;
if (remainderCheck / range == 0) {
cout << "Color 0 error" << endl;
// still need to find the RGB value for these cases
}
else {
color = remainderCheck / range;
fill(colorVector.begin(),colorVector.end()+3,color);
dataVector.at(i).at(j) = colorVector; // <-- DOESN'T WORK
}
}
}
}
My knowledge with C++ is very limited so any help would be greatly appreciated. Also if you have any advice for the other comment dealing with the / operator issues in the same chunk of code, that too would also me incredibly appreciated.
Here are the actual instructions for this specific part:
Step 3 - Compute the color for each part of the map and store
The input data file contains the elevation value for each cell in the map. Now you need to compute the color (in a gray scale between white and black) to use to represent these evaluation values. The shade of gray should be scaled to the elevation of the map.
Traditionally, images are represented and displayed in electronic systems (such as TVs and computers) through the RGB color model, an additive color model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. In this model, colors are represented through three integers (R, G, and B) values between 0 and 255. For example, (0, 0, 255) represents blue and (255, 255, 0) represents yellow. In RGB color, if each of the three RGB values are the same, we get a shade of gray. Thus, there are 256 possible shades of gray from black (0,0,0) to middle gray (128,128,128), to white (255,255,255).
To make the shade of gray, you should use the min and max values in the 2D vector to scale each integer (elevation data) to a value between 0 and 255 inclusive. This can be done with the following equation:
color =(elevation - min elevation)(max elevation - min elevation) * 255
Check your math to ensure that you are scaling correctly. Check your code to make sure that your arithmetic operations are working as you want. Recall that if a and b are variables declared as integers, the expression a/b will be 0 if a==128 and b==256.
As you compute the shade of grey, store that value in three parallel vectors for R, G and B. Putting the same value for R, G and B will result in grey. The structure of the vector should mirror the vector with the elevation data.
Your professor is asking you to make three additional vector<vector<int>>s: 1 for each of R, G, and B. (I do not know why you need three separate vectors: they will have identical values, since for grayscale R==G==B for every element. Still, follow instructions.)
typedef std::vector <int> row_type;
typedef std::vector <row_type> image_type;
image_type dataVector( rows, row_type( columns ) );
image_type R ( rows, row_type( columns ) );
image_type G ( rows, row_type( columns ) );
image_type B ( rows, row_type( columns ) );
Also, be careful whenever you do something like fill(foo.begin(),foo.end()...). Attempting to fill beyond the end of the container (foo.end()+3) is undefined behavior.
Load your dataset into dataVector as before, find your min and max, then for each element find the grayscale value (in [0,255]). Assign that value to each corresponding element of R, G, and B.
Once you have those three square vectors, you can use them to create your PPM file.

Incorrect Pattern Image Generation in OpenCV

Content: Image Processing in OpenCV C++.
The Requirement is to create tiles of Mat pattern of size 256 X 256 on an outer Mat Image. The user specifies the width and the height of the outer Mat Image.
To do this, I created the below OpenCV C++ function:
Mat GenerateDiagonalFade(int width, int height)
{
// Creating a Mat Image in user defined dimension
Mat image(height, width, CV_8UC1, Scalar(0));
//Looping through all rows and columns of the outer Image
for (int row = 0; row < image.rows; row ++)
{
for (int col = 0; col < image.cols; col ++)
{
//Here, I am giving the condition to access the pixel values
//The pattern should be 255 X 255 and they must fill in the entire image
if ((row % 256 + col % 256) <= 255)
{
image.at<uchar>(row, col) = (row % 256 + col % 256);
}
else
{
//Here is where I get error
image.at<uchar>(row, col) = abs(row % 256 - col % 256);
}
}
}
return image;
}
If you can see the else statement above, I tried to make the inverse of the first condition and make the value absolute.
The output I get is as seen below:
The Expected Output is the inverse of the first part of the diagonal. Darker to lighter shade towards the diagonal.
I tried replacing abs(row % 256 - col % 256); with many statements. I am struct with the output.
The changes should be made only in the else statement. Rest of my code is correct as half of my output( top diagonal) is right.
I appreciate any help from you in order to solve this. Trust me, it's quite interesting to work out all graphical[X-Y axis] and mathematical calculations[pixel access] to get the desired output.
I would begin by splitting the problem into two parts:
Generating a single tile containing the correct pattern
Using that tile (or algorithm) to generate the whole image
Generating a Tile
The goal is to generate a 256x256 grayscale image containing a gradient such that:
Top left corner is all black
Bottom right corner is all black
The diagonal going from bottom left to top right is all white
You got the part above the diagonal right, but let's inspect that anyway.
The coordinates of the top left corner are (0, 0) and we expect intensity of 0. --> row + col == 0
The coordinates of one end of the diagonal are (255, 0) and we expect intensity of 255. --> row + col == 255
The other end of the diagonal is at (0, 255) -> row + col == 255
Let's try another point on the diagonal, (254,1) --> again row + col == 255
OK, now a point just above the diagonal, (254,0) -> row + col == 254 -- slightly less white, as we would expect.
Next, let's try a point just below the diagonal, say (255, 1) --> row + col == 256. If we cast this to an 8 bit integer, we get a 0, yet we expect 254, just like in the previous case.
Finally, bottom right corner (255, 255) -> row + col == 510. If we cast this to an 8 bit integer, we get a 254, yet we expect 0.
Let's try something:
256 + 254 == 510
510 + 0 == 510
And we see an algorithm:
* If the sum of row + col is less than 256, then use the sum
* Otherwise subtract the sum from 510 and use the result
Sample code:
cv::Mat make_tile()
{
int32_t const TILE_SIZE(256);
cv::Mat image(TILE_SIZE, TILE_SIZE, CV_8UC1);
for (int32_t r(0); r < TILE_SIZE; ++r) {
for (int32_t c(0); c < TILE_SIZE; ++c) {
int32_t sum(r + c);
if (sum < TILE_SIZE) {
image.at<uint8_t>(r, c) = static_cast<uint8_t>(sum);
} else {
image.at<uint8_t>(r, c) = static_cast<uint8_t>(2 * (TILE_SIZE - 1) - sum);
}
}
}
return image;
}
Single tile:
Generating Image of Tiles
Now that we have a complete tile, we can simply generate the full image by iterating over tile-sized ROIs of the target image, and copying a tile ROI of identical size to them.
Sample code:
#include <opencv2/opencv.hpp>
#include <cstdint>
cv::Mat make_tile()
{
int32_t const TILE_SIZE(256);
cv::Mat image(TILE_SIZE, TILE_SIZE, CV_8UC1);
for (int32_t r(0); r < TILE_SIZE; ++r) {
for (int32_t c(0); c < TILE_SIZE; ++c) {
int32_t sum(r + c);
if (sum < TILE_SIZE) {
image.at<uint8_t>(r, c) = static_cast<uint8_t>(sum);
} else {
image.at<uint8_t>(r, c) = static_cast<uint8_t>(2 * (TILE_SIZE - 1) - sum);
}
}
}
return image;
}
int main()
{
cv::Mat tile(make_tile());
cv::Mat result(600, 800, CV_8UC1);
for (int32_t r(0); r < result.rows; r += tile.rows) {
for (int32_t c(0); c < result.cols; c += tile.cols) {
// Handle incomplete tiles
int32_t end_r(std::min(r + tile.rows, result.rows));
int32_t end_c(std::min(c + tile.cols, result.cols));
// Get current target tile ROI and source ROI of same size
cv::Mat target_roi(result(cv::Range(r, end_r), cv::Range(c, end_c)));
cv::Mat source_roi(tile(cv::Range(0, target_roi.rows), cv::Range(0, target_roi.cols)));
// Copy the tile
source_roi.copyTo(target_roi);
}
}
cv::imwrite("gradient.png", tile);
cv::imwrite("gradient_big.png", result);
}
Complete image:

How to find the pixel value that corresponds to a specific number of pixels?

Assume that I have a grayscale image in OpenCV.
I want to find a value so that 5% of pixels in the images have a value greater than it.
I can iterate over pixels and find number of pixels with the same value and then from the result find the value that %5 of pixel are above my value, but I am looking for a faster way to do this. Is there any such technique in OpenCV?
I think histogram would help, but I am not sure how I can use it.
You need to:
Compute the cumulative histogram of your pixel values
Find the bin whose value is greater than 95% (100 - 5) of the total number of pixels.
Given an image uniformly random generated, you get an histogram like:
and the cumulative histogram like (you need to find the first bin whose value is over the blue line):
Then you need to find the proper bin. You can use std::lower_bound function to find the correct value, and std::distance to find the corresponding bin number (aka the value you want to find). (Please note that with lower_bound you'll find the element whose value is greater or equal to the given value. You can use upper_bound to find the element whose value is strictly greater then the given value)
In this case it results to be 242, which make sense for an uniform distribution from 0 to 255, since 255*0.95 = 242.25.
Check the full code:
#include <opencv2\opencv.hpp>
#include <vector>
#include <algorithm>
using namespace std;
using namespace cv;
void drawHist(const vector<int>& data, Mat3b& dst, int binSize = 3, int height = 0, int ref_value = -1)
{
int max_value = *max_element(data.begin(), data.end());
int rows = 0;
int cols = 0;
float scale = 1;
if (height == 0) {
rows = max_value + 10;
}
else {
rows = height;
scale = float(height) / (max_value + 10);
}
cols = data.size() * binSize;
dst = Mat3b(rows, cols, Vec3b(0, 0, 0));
for (int i = 0; i < data.size(); ++i)
{
int h = rows - int(scale * data[i]);
rectangle(dst, Point(i*binSize, h), Point((i + 1)*binSize - 1, rows), (i % 2) ? Scalar(0, 100, 255) : Scalar(0, 0, 255), CV_FILLED);
}
if (ref_value >= 0)
{
int h = rows - int(scale * ref_value);
line(dst, Point(0, h), Point(cols, h), Scalar(255,0,0));
}
}
int main()
{
Mat1b src(100, 100);
randu(src, Scalar(0), Scalar(255));
int percent = 5; // percent % of pixel values are above a val
int val; // I need to find this value
int n = src.rows * src.cols; // Total number of pixels
int th = cvRound((100 - percent) / 100.f * n); // Number of pixels below val
// Histogram
vector<int> hist(256, 0);
for (int r = 0; r < src.rows; ++r) {
for (int c = 0; c < src.cols; ++c) {
hist[src(r, c)]++;
}
}
// Cumulative histogram
vector<int> cum = hist;
for (int i = 1; i < hist.size(); ++i) {
cum[i] = cum[i - 1] + hist[i];
}
// lower_bound returns an iterator pointing to the first element
// that is not less than (i.e. greater or equal to) th.
val = distance(cum.begin(), lower_bound(cum.begin(), cum.end(), th));
// Plot histograms
Mat3b plotHist, plotCum;
drawHist(hist, plotHist, 3, 300);
drawHist(cum, plotCum, 3, 300, *lower_bound(cum.begin(), cum.end(), th));
cout << "Value: " << val;
imshow("Hist", plotHist);
imshow("Cum", plotCum);
waitKey();
return 0;
}
Note
The histogram drawing function is an upgrade from a former version I posted here
You can use calcHist to compute the histograms, but I personally find easier to use the aforementioned method for 1D histograms.
1) Determine the height and the width of the image, h and w.
2) Determine what 5% of the total number of pixels is (X)...
X = int(h * w * 0.05)
3) Start at the brightest bin in the histogram. Set total T = 0.
4) Add the number of pixels in this bin to your total T. If T is greater than X, you are finished and the value you want is the lower limit of the range of the current histogram bin.
3) Move to the next darker bin in your histogram. Goto 4.

How do I compute the brightness histogram aggregated by column in OpenCV C++

I want to segment car plate to get separate characters.
I found some article, where such segmentation performed using brightness histograms (as i understand - sum of all non-zero pixels).
How can i calculate such histogram? I would really appreciate for any help!
std::vector<int> computeColumnHistogram(const cv::Mat& in) {
std::vector<int> histogram(in.cols,0); //Create a zeroed histogram of the necessary size
for (int y = 0; y < in.rows; y++) {
p_row = in.ptr(y); ///Get a pointer to the y-th row of the image
for (int x = 0; x < in.cols; x++)
histogram[x] += p_row[x]; ///Update histogram value for this image column
}
//Normalize if you want (you'll get the average value per column):
// for (int x = 0; x < in.cols; x++)
// histogram[x] /= in.rows;
return histogram;
}
Or use reduce as suggested by Berak, either calling
cv::reduce(in, out, 0, CV_REDUCE_AVG);
or
cv::reduce(in, out, 0, CV_REDUCE_SUM, CV_32S);
out is a cv::Mat, and it will have a single row.