Given an R,G,B triplet and a factor F, how do I calculate a “watermark” version of the color? - language-agnostic

I have an (R, G, B) triplet, where each color is between 0.0 and 1.0 . Given a factor F (0.0 means the original color and 1.0 means white), I want to calculate a new triplet that is the “watermarked” version of the color.
I use the following expression (pseudo-code):
for each c in R, G, B:
new_c ← c + F × (1 - c)
This produces something that looks okayish, but I understand this introduces deviations to the hue of the color (checking the HSV equivalent before and after the transformation), and I don't know if this is to be expected.
Is there a “standard” (with or without quotes) algorithm to calculate the “watermarked” version of the color? If yes, which is it? If not, what other algorithms to the same effect can you tell me?

Actually this looks like it should give the correct hue, minus small variations for arithmetic rounding errors.
This is certainly a reasonable, simple was to achieve a watermark effect. I don't know of any other "standard" ones, there are a few ways you could do it.
Alternatives are:
Blend with white but do it non-linearly on F, e.g. new_c = c + sqrt(F)*(1-c), or you could use other non-linear functions - it might help the watermark look more or less "flat".
You could do it more efficiently by doing the following (where F takes the range 0..INF):
new_c = 1 - (1-c)/pow(2, F)
for real pixel values (0..255) this would convert into:
new_c = 255 - (255-c)>>F
Not only is that reasonably fast in integer arithmetic, but you may be able to do it in a 32b integer in parallel.

Why not just?
new_c = F*c
I think you should go first over watermarking pixels and figure out if it should be darker or lighter.
For lighter the formula might be
new_c=1-F*(c-1)

Related

Cut ultrasound signal between specific values using Octave

I have an ultrasound wave (graph axes: Volt vs microsecond) and need to cut the signal/wave between two specific value to further analyze this clipping. My idea is to cut the signal between 0.2 V (y-axis). The wave is sine shaped as shown in the figure with the desired cutoff points in red
In my current code, I'm cutting the signal between 1900 to 4000 ms (x-axis) (Aa = A(1900:4000);) and then I want to make the aforementioned clipping and proceed with the code.
Does anyone know how I could do this y-axis clipping?
Thanks!! :)
clear
clf
pkg load signal
for k=1:2
w=1
filename=strcat("PCB 2.1 (",sprintf("%01d",k),").mat")
load(filename)
Lthisrun=length(A);
Pico(k,1:Lthisrun)=A;
Aa = A(1900:4000);
Ah= abs(hilbert(Aa));
step=100;
hold on
i=1;
Ac=0;
for index=1:step:3601
Ac(i+1)=Ac(i)+Ah(i);
i=i+1
r(k)=trapz(Ac)
end
end
ok, you want to just look at values 'above the noise' in your data. Or, in this case, 'clip out' everything below 0.2V. the easiest way to do this is with logical indexing. You can take an array and create a sub array eliminating everything that doesn't meet a certain logical condition. See this example:
f = #(x) sin(x)./x;
x = [-100:.1:100];
y = f(x);
plot(x,y);
figure;
x_trim = x(y>0.2);
y_trim = y(y>0.2);
plot(x_trim, y_trim);
From your question it looks like you want to do the clipping after applying the horizontal windowing from 1900-4000. (you say that that is in milliseconds, but your image shows the pulse being much sooner than 1900 ms). In any case, something like
Ab = Aa(Aa > 0.2);
will create another array Ab that will only contain the portions of Aa with values above 0.2. You may need to do something similar (see the example) for the horizontal axis if your x-data is not just the element index.

Inverted Smoothstep?

I am currently trying to simulate ballistics on an object, that is otherwise not affected by physics. To be precise, I have a rocket-like projectile, that is following an parabolic arc from origin to target with a Lerp. To make it more realistic, I want it not to move at constant speed, but to slow down towards the climax and speed up on its way back down.
I have used the Mathf.Smoothstep function to do the exact opposite of what i need on other objects, i.e. easing in and out of the motion.
So my question is: How do I get an inverted Smoothstep?
I found out that what i would need is actually the inverted formula to smoothstep [ x * x*(3 - 2*x) ], but being not exactly a math genius, I have no idea how to do that. All I got from online calculators was some pretty massive new function, which I'm afraid would not be very efficient.
So maybe there is a function that comes close to an inverted smoothstep, but isn't as complex to compute.
Any help on this would be much appreciated
Thanks in advance,
Tux
Correct formula is available here:
https://www.shadertoy.com/view/MsSBRh
Solution by Inigo Quilez and TinyTexel
Flt SmoothCubeInv(Flt y)
{
if(y<=0)return 0;
if(y>=1)return 1;
return 0.5f-Sin(asinf(1-2*y)/3);
}
I had a similar problem. For me, mirroring the curve in y = x worked:
So an implementation example would be:
float Smooth(float x) {
return x + (x - (x * x * (3.0f - 2.0f * x)));
}
This function has no clamping, so that may have to be added if x can go outside the 0 to 1 interval.
Wolfram Alpha example
If you're moving transforms, it is often a good idea to user iTween or similar animation libraries instead of controlling animation yourself. They have a an easy API and you can set up easing mode too.
But if you need this as a math function, you can use something like this:
y = 0.5 + (x > 0.5 ? 1 : -1) * Mathf.Pow(Mathf.Abs(2x - 1),p)/2
Where p is the measure of steepness that you want. Here's how it looks:
You seem to want a regular parabola. See the graph of this function:
http://www.wolframalpha.com/input/?i=-%28x%2A2-1%29%5E2%2B1
Which is the graph that seems to do what you want: -(x*2-1)^2+1
It goes from y=0 to y=1 and then back again between x=0 and x=1, staying a bit at the top around x=0.5 . It's what you want, if I understood it correctly.
Other ways to write this function, according to wolfram alpha, would be -(4*(x-1)*x) and (4-4*x)*x
Hope it helps.

Printing a table with sage math

The assignment is to construct a two-column table that starts at x= -4 and ends with x= 5 with one unit increments between consecutive x values. It should have column headings ‘x’ and ‘f(x)’. I can't find anything helpful on html.table(), which is what we're supposed to use.
This what I have so far. I just have no idea what to put into the html.table function.
x = var('x')
f(x) = (5 * x^2) - (9 * x) + 4
html.table()
You might want to have a look at sage's reference documentation page on html.table
It contains the following valuable information :
table(x, header=False)
Print a nested list as a HTML table. Strings of html will be parsed for math inside dollar and double-dollar signs. 2D graphics will be displayed in the cells. Expressions will be latexed.
INPUT:
x – a list of lists (i.e., a list of table rows)
header – a row of headers. If True, then the first row of the table is taken to be the header.
There is also an example for sin (instead of f) with x in 0..3 instead of -4..5, that you can probably adapt pretty easily :
html.table([(x,sin(x)) for x in [0..3]], header = ["$x$", "$\sin(x)$"])
#Cimbali has a great answer. For completeness, I'll point out that you should be able to get this information with
html.table?
or, in fact,
table?
since I would say we want to advocate the more general table function, which has a lot of good potential for you.

Freefem++: Solving poisson equation with numerical function

I am using Freefem++ to solve the poisson equation
Grad^2 u(x,y,z) = -f(x,y,z)
It works well when I have an analytical expression for f, but now I have an f numerically defined (i.e. a set of data defined on a mesh) and I am wondering if I can still use Freefem++.
I.e. typical code (for a 2D problem in this case), looks like the following
mesh Sh= square(10,10); // mesh generation of a square
fespace Vh(Sh,P1); // space of P1 Finite Elements
Vh u,v; // u and v belongs to Vh
func f=cos(x)*y; // analytical function
problem Poisson(u,v)= // Definition of the problem
int2d(Sh)(dx(u)*dx(v)+dy(u)*dy(v)) // bilinear form
-int2d(Sh)(f*v) // linear form
+on(1,2,3,4,u=0); // Dirichlet Conditions
Poisson; // Solve Poisson Equation
plot(u); // Plot the result
I am wondering if I can define f numerically, rather than analytically.
Mesh & space Definition
We define a square unit with Nx=10 mesh and Ny=10 this provides 11 nodes on x axis and the same for y axis.
int Nx=10,Ny=10;
int Lx=1,Ly=1;
mesh Sh= square(Nx,Ny,[Lx*x,Ly*y]); //this is the same as square(10,10)
fespace Vh(Sh,P1); // a space of P1 Finite Elements to use for u definition
Conditions and problem statement
We are not going to use solve but we ll handle matrix (a more sophisticated way to solve with FreeFem).
First we define CL for our problem (Dirichlet ones).
varf CL(u,psi)=on(1,2,3,4,u=0); //you can eliminate border according to your problem state
Vh u=0;u[]=CL(0,Vh);
matrix GD=CL(Vh,Vh);
Then we define the problem. Instead of writing dx(u)*dx(v)+dy(u)*dy(v) I suggest to use macro, so we define div as following but pay attention macro finishes by // NOT ;.
macro div(u) (dx(u[0])+dy(u[1])) //
So Poisson bilinear form becomes:
varf Poisson(u,v)= int2d(Sh)(div(u)*div(v));
After we extract Stifness Matrix
matrix K=Poisson(Vh,Vh);
matrix KD=K+GD; //we add CL defined above
We proceed for solving, UMFPACK is a solver in FreeFem no much attention to this.
set(KD,solver=UMFPACK);
And here what you need. You want to define a value of function f on some specific nodes. I'm going to give you the secret, the poisson linear form.
real[int] b=Poisson(0,Vh);
You define value of the function f at any node you want to do.
b[100]+=20; //for example at node 100 we want that f equals to 20
b[50]+=50; //and at node 50 , f equals to 50
We solve our system.
u[]=KD^-1*b;
Finally we get the plot.
plot(u,wait=1);
I hope this will help you, thanks to my internship supervisor Olivier, he always gives to me tricks specially on FreeFem. I tested it, it works very well. Good luck.
The method by afaf works in the case when the function f is a free-standing one. For the terms like int2d(Sh)(f*u*v), another solution is required. I propose (actually I have red it somewhere in Hecht's manual) an approach that covers both cases. However, it works only for P1 finite elements, for which the degrees of freedom are coincided with the mesh nodes.
fespace Vh(Th,P1);
Vh f;
real[int] pot(Vh.ndof);
for(int i=0;i<Vh.ndof;i++){
pot[i]=something; //assign values or read them from a file
}
f[]=pot;

Get the most probable color from a words set

Are there any libraries existing or methods that let you to figure out the most probable color for a words set? For example, cucumber, apple, grass, it gives me green color. Did anyone work in that direction before?
If i have to do that, i will try to search images based on the words using google image or others and recognize the most common color of top n results.
That sounds like a pretty reasonable NLP problem and one thats very easy to handle via map-reduce.
Identify a list of words and phrases that you call colors ['blue', 'green', 'red', ...].
Go over a large corpus of sentences, and for the sentences that mention a particular color, for every other word in that sentence, note down (word, color_name) in a file. (Map Step)
Then for each word you have seen in your corpus, aggregate all the colors you have seen for it to get something like {'cucumber': {'green': 300, 'yellow': 34, 'blue': 2}, 'tomato': {'red': 900, 'green': 430'}...} (Reduce Step)
Provided you use a large enough corpus (something like wikipedia), and you figure out how to prune really small counts, rare words, you should be able to make pretty comprehensive and robust dictionary mapping millions of the items to their colors.
Another way to do that is to do a text search in google for combinations of colors and the word in question and take the combination with the highest number of results. Here's a quick Python script for that:
import urllib
import json
import itertools
def google_count(q):
query = urllib.urlencode({'q': q})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
search_response = urllib.urlopen(url)
search_results = search_response.read()
results = json.loads(search_results)
data = results['responseData']
return int(data['cursor']['estimatedResultCount'])
colors = ['yellow', 'orange', 'red', 'purple', 'blue', 'green']
# get a list of google search counts
res = [google_count('"%s grass"' % c) for c in colors]
# pair the results with their corresponding colors
res2 = list(itertools.izip(res, colors))
# get the color with the highest score
print "%s is %s" % ('grass', sorted(res2)[-1][1])
This will print:
grass is green
Daniel's and Xi.lin's answers are very good ideas. Along the same axis, we could combine both with an approach similar to Xilin's but more simple: Query Google Image with the word you want to find the color associated with + a "Color" filter (see in the lower left bar). And see which color yields more results.
I would suggest using a tightly defined set of sources if possible such as Wikipedia and Wordnet.
Here, for example, is Wordnet for "panda":
S: (n) giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca
(large black-and-white herbivorous mammal of bamboo forests of China and Tibet;
in some classifications considered a member of the bear family or of a separate
family Ailuropodidae)
S: (n) lesser panda, red panda, panda, bear cat, cat bear,
Ailurus fulgens (reddish-brown Old World raccoon-like carnivore;
in some classifications considered unrelated to the giant pandas)
Because of the concise, carefully constructed language it is highly likely that any colour words will be important. Here you can see that pandas are both black-and-white and reddish-brown.
If you identify subsections of Wikipedia (e.g. "Botanical Description") this will help to increase the relevance of your results. Also the first image in Wikipedia is very likely to be the best "definitive" one.
But, as with all statistical methods, you will get false positives (and negatives , though these are probably less of a problem).