Desaturating Colours in CTL - c

Looking to create a CTL with a colour transform that is de-saturates a pair of opposing colours.
My example below works: but not as expected:
__DEVICE__ float3 squeeze_GM(float percentage, float R, float G, float B) {
float rOut = R - (((percentage/2) / 100) * R);
float gOut = G - ((percentage / 100) * G);
float bOut = B - (((percentage/2) / 100) * B);
return make_float3(rOut, gOut, bOut);
}
__DEVICE__ float3 transform(int p_Width, int p_Height, int p_X, int p_Y, float p_R, float p_G, float p_B){
float3 result = squeeze_GM(15, p_R, p_G, p_B);
return result;
}
I would like to squeeze the green and magenta, so as to de-saturate these colours by a certain percentage passed to the squeeze_GM function.
Does anyone have any details how I might get this transform? At the moment I think I am just making the RGB values darker by a certain percentage. Would I need to average my R and B results?

Look at Wiki for HUE
An idea could be:
void HSV(uint8_t rgb[]){
int32_t r,g,b;
int32_t MaxVal,Minim,MedValue,MinValue;
int32_t Huecalc=0;
r=rgb[0];
g=rgb[1];
b=rgb[2];
Minim=255;
if(Minim>r)Minim=r; //if red=128
if(Minim>g)Minim=g; //if green=200
if(Minim>b)Minim=b; //if blue= 254
// Minim = 128;
MaxVal=0;
if(MaxVal<r)MaxVal=r; //if red=128
if(MaxVal<g)MaxVal=g; //if green=200
if(MaxVal<b)MaxVal=b; //if blue= 254
// MaxVal = 254
MedValue=MaxVal-Minim; // MedValue = 254-128 > 0
MinValue=Minim; // MinValue = 128
if(MedValue>0){
if(MaxVal==r)Huecalc=0L*MedValue+(g-b); // Wiki HUE THEORY explain this
if(MaxVal==g)Huecalc=2L*MedValue+(b-r);
if(MaxVal==b)Huecalc=4L*MedValue+(r-g);
HUE=Huecalc*254/6/MedValue; // %254
}
if(MinValue>0){
SAT=MedValue*254/MinValue; // %254
}
}

Related

How to zoom/move into the mandelbrot set

I'm doing the Mandelbrot set in c as a school project.<br>
This is my code:
int mandelbrot(int x, int y, t_data *data)
{
double complex c;
double complex z;
double cx;
double cy;
int i;
cx = map(x, 0, WIDTH, data->min, data->max);
cy = map(y, 0, HEIGHT, data->min , data->max);
c = cx + cy * I;
z = 0;
i = 0;
while (i < data->max_iteration)
{
z = z * z + c;
if (creal(z) * creal(z) + cimag(z) * cimag(z) > 4)
break;
i++;
}
return (get_color(i, *data));
}
I used the map() function to convert the window coordinates to the complex coordinates
and I used it to get the cursor coordinates in the complex space too:
double map(double value, double screen_min, double screen_max
, double image_min, double image_max)
{
return ((value - screen_min ) \
* (image_max - image_min) \
/ (screen_max - screen_min) \
+ image_min);
}
the data is a struct that has the variables I need for the mand:
typedef struct mouse
{
double cursor_cx; // cursor x coordinates in the complex plane
double cursor_cy; // cursor x coordinates in the complex plane
double min; // the minimum edge of the mand initialized to -2
double max; // initialized to 2
int max_iteration; // initialized to 100
mlx_t *mlx; // the window I guess
mlx_image_t *g_img; // the img I'll draw my pixels to
} t_data;
My problem now is moving the mandelbrot around and zooming in and out.<br>
1st: I managed to zoom in and out by changing the min and max:
void zoom_hook(double xdelta, double ydelta, void *param)
{
int32_t cursor_x = get_cursor_x();
int32_t cursor_y = get_cursor_x();
float step;
step = 0.1;
t_data *data = param;
(void)xdelta;
if (ydelta > 0)
{
data->min += step;
data->max -= step;
}
else if (ydelta < 0)
{
data->min -= step;
data->max += step;
}
}
but when I zoom in a few times the mand get's inverted and starts zooming out even tho I'm zooming in<br>
that's because min is moving from -2 to 0 then if I zoom more then that from 0 to 2
and vise versa for max
so I need a better way of zooming in, I'm expecting to be able to zoom in forever as long as it is within the limits of the computer. but right now my mand get's inverted before reaching that limit.
and more than that I can get the cursor x and y positions so I want to zoom in into those coordinates.
2nd: I need to move my `mand` and this is what I tried but it doesn't work It's zooming in and out but in diagonal way:
void key_hook(void *param)
{
t_data *data;
float step;
step = 0.1;
data = param;
if (mlx_is_key_down(data->mlx, MLX_KEY_ESCAPE))
mlx_close_window(data->mlx);
if (mlx_is_key_down(data->mlx, MLX_KEY_RIGHT))
data->min -= step;
if (mlx_is_key_down(data->mlx, MLX_KEY_LEFT))
data->min += step;
if (mlx_is_key_down(data->mlx, MLX_KEY_UP))
data->max += step;
if (mlx_is_key_down(data->mlx, MLX_KEY_DOWN))
data->max -= step;
}
I'm expecting it to move to the directions right, left, up and down.<br>
So I need some helpt to move and zoom my mandelbrot set.
Thanks in advance.

Scaling a point from one 2d-space to another

The input to my program is a (x, y) integer coordinate inside the blue region of this circle of radius 100. I want to scale the input coordinate from the blue area to the red area, maintaining the the x and y ratios.
(link to the Desmos plot: https://www.desmos.com/calculator/61f4y2r7r4)
I know how to do this with one dimension - this answer gives a good overview on performing linear scaling. I attempted to apply this approach to the x and y axes separately. Here is some example code that I wrote to model the image.
#include <math.h>
#include <stdio.h>
#define RADIUS 100
static int find_point_on_circumference(int val) {
return sqrt(RADIUS * RADIUS - val * val);
}
static int scale(int val, int min_old, int max_old, int min_new, int max_new) {
return (max_old == min_old)
? val
: (((val - min_old) * (max_new - min_new)) / (max_old - min_old) + min_new);
}
int main() {
int x = 15;
int y = 96;
int boundary_old_x = 10;
int boundary_old_y = 10;
int boundary_new_x = 30;
int boundary_new_y = 20;
int new_x = scale(
x,
boundary_old_x,
find_point_on_circumference(y),
boundary_new_x,
find_point_on_circumference(y));
int new_y = scale(
y,
boundary_old_y,
find_point_on_circumference(x),
boundary_new_y,
find_point_on_circumference(x));
if (sqrt(new_x * new_x + new_y * new_y) <= RADIUS) {
printf("SUCCESS\n");
} else {
printf("FAIL\n");
}
return 0;
}
For this particular input, (15, 96), the result is outside of the circle. I can see that the reason for that is that my max-x bound is less than my min-x bound. I'm just not sure how I should be applying this scaling correctly in the first place.

C Mandelbrot Set Coloring

I am working on the following code in C. So far it has all been working and it is zoomed to the correct level, etc, however I am struggling with getting the colors to work as I want. Ideally I would like to end up with something like this regardless of color:
however my program as it is below currently produces something like this:
Therefore, I would appreciate any help I could get with making the colors turn out as I want them to.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define ITERMAX 100.0
#define DIVERGING 1.1
#define XMAX 500
#define YMAX 500
#define COLORINTENSITY 255
/* allow up to ITERMAX feedbacks searching for convergence
for the feedback
z0 = 0 + 0i
znew = z^2 + c
If we have not diverged to distance DIVERGING before ITERMAX feedbacks
we will assume the feedback is convergent at this value of c.
We will report divergence if |z|^2 > DIVERGING
*/
/* We will print color values for each pixel from (0, 0) to (XMAX, YMAX)
The color of pixel (cx, cy) will be set by convergent()
or by divergent()
depending on the convergence or divergence of the feedback
when c = cx + icy
*/
/* The max value of the red, green, or blue component of a color */
void convergent(); /* one color for convergence */
void divergent(); /* a different color for divergence */
void feedback(double *x, double *y, double cx, double cy);
void pixel(char red, char green, char blue);
FILE *fp;
int main()
{
fp = fopen("mandelbrot.ppm", "wb");
double x, y, cx, cy;
int iteration,squarex, squarey, pixelx, pixely;
double grow=1.0;
/* header for PPM output */
fprintf(fp, "P6\n# CREATOR: EK, BB, RPJ via the mandel program\n");
fprintf(fp, "%d %d\n%d\n",XMAX, YMAX, COLORINTENSITY);
for (pixely = 0; pixely < YMAX; pixely++) {
for (pixelx = 0; pixelx < XMAX; pixelx++) {
cx = (((float)pixelx)/((float)XMAX)-0.5)/grow*3.0-0.7;
cy = (((float)pixely)/((float)YMAX)-0.5)/grow*3.0;
x = 0.0; y = 0.0;
for (iteration=1;iteration<ITERMAX;iteration++) {
feedback(&x, &y, cx, cy);
if (x*x + y*y > 100.0) iteration = 1000;
}
if (iteration==ITERMAX) {
iteration = x*x + y*y;
pixel((char) 0, (char) 0, (char) 0);
}
else {
iteration = sqrt(x*x + y*y);
pixel((char) iteration, (char) 0, (char) iteration);
}
}
}
}
void feedback(double *x, double *y, double cx, double cy) {
/* Update x and y according to the feedback equation
xnew = x^2 - y^2 + cx
ynew = 2xy + cy
(these are the real and imaginary parts of the complex equation:
znew = z^2 + c)
*/
double xnew = (*x) * (*x) - (*y) * (*y) + cx;
double ynew = 2 * *x * *y + cy;
*x = xnew;
*y = ynew;
}
void pixel(char red, char green, char blue) {
/* put a r-g-b triple to the standard out */
fputc(red, fp);
fputc(green, fp);
fputc(blue, fp);
}
To fix the banding, you need to iterate over your tables to find your maximum value for the iteration count, then scale your other values to be relative to this max (ie. normalize the values). You may also wish to logarithmically rescale the values to adjust the slope of the color-change.
And you probably don't want to work directly in RGB space. If you define your colors in HSB space, you can set a constant hue and saturation, and vary the brightness proportionally to the normalized iteration counts.

Reverse the Fish-eye Distortion(I've used openCV with VC++)

I've made a simulation of fish eye distortion.
I want to develop a reverse program that can convert the distorted image to normal image.
I've tried to use undistortPonts() function but couldn't understand the input(dist-coefficient).
cv.UndistortPoints(distorted, undistorted, intrinsics, dist_coeffs)
My code for fish eye distortion:
#include "stdio.h"
#include <cv.h>
#include <highgui.h>
#include <math.h>
#include <iostream>
void sampleImage(const IplImage* arr, float idx0, float idx1, CvScalar& res)
{
if(idx0<0 || idx1<0 || idx0>(cvGetSize(arr).height-1) || idx1>(cvGetSize(arr).width-1))
{
res.val[0]=0;
res.val[1]=0;
res.val[2]=0;
res.val[3]=0;
return;
}
float idx0_fl=floor(idx0);
float idx0_cl=ceil(idx0);
float idx1_fl=floor(idx1);
float idx1_cl=ceil(idx1);
CvScalar s1=cvGet2D(arr,(int)idx0_fl,(int)idx1_fl);
CvScalar s2=cvGet2D(arr,(int)idx0_fl,(int)idx1_cl);
CvScalar s3=cvGet2D(arr,(int)idx0_cl,(int)idx1_cl);
CvScalar s4=cvGet2D(arr,(int)idx0_cl,(int)idx1_fl);
float x = idx0 - idx0_fl;
float y = idx1 - idx1_fl;
res.val[0]= s1.val[0]*(1-x)*(1-y) + s2.val[0]*(1-x)*y + s3.val[0]*x*y + s4.val[0]*x*(1-y);
res.val[1]= s1.val[1]*(1-x)*(1-y) + s2.val[1]*(1-x)*y + s3.val[1]*x*y + s4.val[1]*x*(1-y);
res.val[2]= s1.val[2]*(1-x)*(1-y) + s2.val[2]*(1-x)*y + s3.val[2]*x*y + s4.val[2]*x*(1-y);
res.val[3]= s1.val[3]*(1-x)*(1-y) + s2.val[3]*(1-x)*y + s3.val[3]*x*y + s4.val[3]*x*(1-y);
}
float xscale;
float yscale;
float xshift;
float yshift;
float getRadialX(float x,float y,float cx,float cy,float k)
{
x = (x*xscale+xshift);
y = (y*yscale+yshift);
float res = x+((x-cx)*k*((x-cx)*(x-cx)+(y-cy)*(y-cy)));
return res;
}
float getRadialY(float x,float y,float cx,float cy,float k)
{
x = (x*xscale+xshift);
y = (y*yscale+yshift);
float res = y+((y-cy)*k*((x-cx)*(x-cx)+(y-cy)*(y-cy)));
return res;
}
float thresh = 1;
float calc_shift(float x1,float x2,float cx,float k)
{
float x3 = x1+(x2-x1)*0.5;
float res1 = x1+((x1-cx)*k*((x1-cx)*(x1-cx)));
float res3 = x3+((x3-cx)*k*((x3-cx)*(x3-cx)));
// std::cerr<<"x1: "<<x1<<" - "<<res1<<" x3: "<<x3<<" - "<<res3<<std::endl;
if(res1>-thresh && res1 < thresh)
return x1;
if(res3<0)
{
return calc_shift(x3,x2,cx,k);
}
else
{
return calc_shift(x1,x3,cx,k);
}
}
int main(int argc, char** argv)
{
IplImage* src = cvLoadImage( "D:\\2012 Projects\\FishEye\\Debug\\images\\grid1.bmp", 1 );
IplImage* dst = cvCreateImage(cvGetSize(src),src->depth,src->nChannels);
IplImage* dst2 = cvCreateImage(cvGetSize(src),src->depth,src->nChannels);
float K=0.002;
float centerX=(float)(src->width/2);
float centerY=(float)(src->height/2);
int width = cvGetSize(src).width;
int height = cvGetSize(src).height;
xshift = calc_shift(0,centerX-1,centerX,K);
float newcenterX = width-centerX;
float xshift_2 = calc_shift(0,newcenterX-1,newcenterX,K);
yshift = calc_shift(0,centerY-1,centerY,K);
float newcenterY = height-centerY;
float yshift_2 = calc_shift(0,newcenterY-1,newcenterY,K);
// scale = (centerX-xshift)/centerX;
xscale = (width-xshift-xshift_2)/width;
yscale = (height-yshift-yshift_2)/height;
std::cerr<<xshift<<" "<<yshift<<" "<<xscale<<" "<<yscale<<std::endl;
std::cerr<<cvGetSize(src).height<<std::endl;
std::cerr<<cvGetSize(src).width<<std::endl;
for(int j=0;j<cvGetSize(dst).height;j++)
{
for(int i=0;i<cvGetSize(dst).width;i++)
{
CvScalar s;
float x = getRadialX((float)i,(float)j,centerX,centerY,K);
float y = getRadialY((float)i,(float)j,centerX,centerY,K);
sampleImage(src,y,x,s);
cvSet2D(dst,j,i,s);
}
}
#if 0
cvNamedWindow( "Source1", 1 );
cvShowImage( "Source1", dst);
cvWaitKey(0);
#endif
cvSaveImage("D:\\2012 Projects\\FishEye\\Debug\\images\\grid3.bmp",dst,0);
cvNamedWindow( "Source1", 1 );
cvShowImage( "Source1", src);
cvWaitKey(0);
cvNamedWindow( "Distortion", 2 );
cvShowImage( "Distortion", dst);
cvWaitKey(0);
#if 0
for(int j=0;j<cvGetSize(src).height;j++)
{
for(int i=0;i<cvGetSize(src).width;i++)
{
CvScalar s;
sampleImage(src,j+0.25,i+0.25,s);
cvSet2D(dst,j,i,s);
}
}
cvNamedWindow( "Source1", 1 );
cvShowImage( "Source1", src);
cvWaitKey(0);
#endif
}
Actually, my original anwser was about the undistortion algorithm for individual points. If you want to undistort a complete image, there is a much simpler technique, as explained in this other thread:
Understanding of openCV undistortion
The outline of the algorithm (which is the one used in OpenCV function undistort()) is as follow. For each pixel of the destination lens-corrected image do:
Convert the pixel coordinates (u_dst, v_dst) to normalized coordinates (x', y') using the inverse of the calibration matrix K,
Apply your lens-distortion model, to obtain the distorted normalized coordinates (x'', y''),
Convert (x'', y'') to distorted pixel coordinates (u_src, v_src) using the calibration matrix K,
Use the interpolation method of your choice to find the intensity/depth associated with the pixel coordinates (u_src, v_src) in the source image, and assign this intensity/depth to the current destination pixel (u_dst, v_dst).
Original answer:
Here is the undistortion algorithm extracted from OpenCV function undistortPoints() :
void dist2norm(const cv::Point2d &pt_dist, cv::Point2d &pt_norm) const {
pt_norm.x = (pt_dist.x-Kcx)/Kfx;
pt_norm.y = (pt_dist.y-Kcy)/Kfy;
int niters=(Dk1!=0.?5:0);
double x0=pt_norm.x, y0=pt_norm.y;
for(int i=0; i<niters; ++i) {
double x2=pt_norm.x*pt_norm.x,
y2=pt_norm.y*pt_norm.y,
xy=pt_norm.x*pt_norm.y,
r2=x2+y2;
double icdist = 1./(1 + ((Dk3*r2 + Dk2)*r2 + Dk1)*r2);
double deltaX = 2*Dp1*xy + Dp2*(r2 + 2*x2);
double deltaY = Dp1*(r2 + 2*y2) + 2*Dp2*xy;
pt_norm.x = (x0-deltaX)*icdist;
pt_norm.y = (y0-deltaY)*icdist;
}
}
If you provide the coordinates of a point in the distorted image in argument pt_dist, it will calculate the normalized coordinates of the associated point and return them in pt_norm. Then, you can obtain the coordinates of the associated point in the undistorted image as
pt_undist = K . [pt_norm.x; pt_norm.y; 1]
where K is the camera matrix.
The standard lens distortion model used by OpenCV is explained at the beginning of this page:
where the distortion coefficients are (k1,k2,p1,p2,k3, k4,k5,k6) (most often we use k4=k5=k6=0).
I don't know what is your model for FishEye distortion, but you can surely adapt the above algorithm to your case. Otherwise, you may use a non-linear optimization algorithm (e.g. Levenberg-Marquardt or any other), to recover the undistorted coordinates from the distorted one.

Why is my ray-traced image entirely black?

I had to generate an image that's a black circle, black being (0, 0 , 0) and white being (1, 1, 1), but I keep getting a completely black image. Here's all my code:
#include "cast.h"
#include "collisions.h"
#include <stdio.h>
#include "math.h"
int cast_ray(struct ray r, struct sphere spheres[], int num_spheres)
{
int isFound;
struct maybe_point mp;
isFound = 0;
for (int i = 0; i < num_spheres; i++)
{
mp = sphere_intersection_point(r, spheres[i]);
if (mp.isPoint == 1)
{
isFound = 1;
}
else
{
isFound = 0;
}
}
return isFound;
}
void print_pixel(double a, double b, double c)
{
int i, j, k;
i = a * 255;
j = b * 255;
k = c * 255;
printf("%d %d %d ", i, j, k);
}
void cast_all_rays(double min_x, double max_x, double min_y, double max_y,
int width, int height, struct point eye,
struct sphere spheres[], int num_spheres)
{
double width_interval, height_interval, y, x;
int intersect;
width_interval = (max_x - min_x)/width;
height_interval = (max_y - min_y)/height;
for (y = max_y; y > min_y; y = y - height_interval)
{
for (x = min_x; x < max_x; x = x + width_interval)
{
struct ray r;
r.p = eye;
r.dir.x = x;
r.dir.y = y;
r.dir.z = 0.0;
intersect = cast_ray(r, spheres, num_spheres);
if (intersect != 0)
{
print_pixel (0, 0, 0);
}
else
{
print_pixel (1, 1, 1);
}
}
I already had functions that I know are correct which find whether or not the ray intersects with a sphere. The function that I used to find intersection points was in the function cast_ray.
sphere_intersection_point(r, spheres[i]);
The print_pixel function translates the integer values by multiplying them with the max color value, which is 255.
And the cast_all_rays function casts rays into the whole scene from our eyes (going through all the x coordinates before changing the y). If the ray intersects with a sphere, the pixel is black, thus, forming a black circle in the end.
And here are the limits for the x, y, and radius (NOTE: I'M USING THE PPM FORMAT):
Eye at <0.0, 0.0, -14.0>.
A sphere at <1.0, 1.0, 0.0> with radius 2.0.
A sphere at <0.5, 1.5, -3.0> with radius 0.5.
min_x at -10, max_x at 10, min_y of -7.5, max_y at 7.5, width=1024, and height=768.
I need to generate an image of a black circle, but I keep getting an image that's completely black. I have a feeling that the problem lies inside the cast_all_rays function, but I just can't seem to find what it is. Help is appreciated! Thanks.
And just in case something went wrong with my testing, here's my test.c file for cast_all_rays:
#include "collisions.h"
#include "data.h"
#include "cast.h"
#include <stdio.h>
void cast_all_rays_tests(void)
{
printf("P3\n");
printf("%d %d\n", 1024, 768);
printf("255\n");
double min_x, max_x, min_y, max_y;
int width, height;
struct point eye;
struct sphere spheres[2];
eye.x = 0.0;
eye.y = 0.0;
eye.z = -14.0;
spheres[0].center.x = 1.0;
spheres[0].center.y = 1.0;
spheres[0].center.z = 0.0;
spheres[0].radius = 2.0;
spheres[1].center.x = 0.5;
spheres[1].center.y = 1.5;
spheres[1].center.z = -3.0;
spheres[1].radius = 0.5;
min_x = -10;
max_x = 10;
min_y = -7.5;
max_y = 7.5;
cast_all_rays(min_x, max_x, min_y, max_y, width, height, eye, spheres, num_spheres);
}
int main()
{
cast_all_rays_tests();
return 0;
}
Not sure if this is the problem you're having, but you should only set isFound if you intersect a sphere. Don't set it if you don't intersect. Otherwise your image will be governed by only the last sphere in the list.
if (mp.isPoint == 1)
{
isFound = 1;
}
//else
//{
// isFound = 0;
//}
Since your image is entirely black, it seems like your intersection code is bung or your field of view is too narrow. If you don't have any joy with the above change, maybe you should post details on your x- and y-limits, the eye position, and the position and radius of the sphere.
One more thing I noticed is r.dir.z = 0.0. Do you subtract the eye position from this to get a direction, or is that your true ray direction? Surely you need to give a non-zero z-direction. Normally you set the x and the y based on your view plane and provide a constant z such as 1 or -1.
[edit]
To make it clearer from the comments below, I believe that you haven't correctly set up your ray direction. Instead you have simply set the direction to be the view-plane's pixel position, ignoring the eye position. The following would be more usual:
struct ray r;
r.p = eye;
r.dir.x = x - eye.x;
r.dir.y = y - eye.y;
r.dir.z = 0.0 - eye.z;

Resources