How alpha blending works with a transparent background in photoshop - graphics

I have two squares: red with color (255, 0, 0) 50% opacity, blue with color (0, 0, 255) 50% opacity
and black opaque background.
At the intersection of these colors, Photoshop shows the color (128, 0, 64) (
photoshp screenshot
).
And I agree whith that. Blue color first blends with black background:
(0, 0, 255) * 0.5 + (0, 0, 0) * ( 1 - 0.5) = (0, 0, 127.5)
alpha = 0.5 + 1 * (1 - 0.5) = 1
Then the result is mixed with red:
(255, 0, 0) * 0.5 + (0, 0, 127.5) * (1 - 0.5) = (127.5, 0, 63.75)
alpha = 0.5 + 1 * (1 - 0.5) = 1
But if background is transparent photoshop gives color (170, 0, 85) with 75% opacity (
photoshp screenshot
).
How does it get that color? I expected (127.5, 0, 127.5) with 75% opacity, because there is nothing in background to blend with.

Following the math described in this article, alpha blending blue square with 50% opacity onto the black background with 0% opacity results in this:
alpha_bg = 0
alpha_fg = 0.5
alpha_blended = alpha_fg + alpha_bg * (1 - alpha_fg) = 0.5
color_blended = ({0, 0, 255} * alpha_fg + {0, 0, 0} * (alpha_bg * (1 - alpha_fg))) / alpha_blended =
({0, 0, 255} * 0.5 + {0, 0, 0} * 0) / 0.5 = {0, 0, 255}
Then, repeating these calculations for blending the red square with 50% opacity on top of the color we calculated above:
alpha_bg = 0.5
alpha_fg = 0.5
alpha_blended = alpha_fg + alpha_bg * (1 - alpha_fg) = 0.5 + 0.5 * (1 - 0.5) = 0.75
color_blended = ({255, 0, 0} * alpha_fg + {0, 0, 255} * (alpha_bg * (1 - alpha_fg))) / alpha_blended =
({255, 0, 0} * 0.5 + {0, 0, 255} * (0.5 * (1 - 0.5))) / 0.75 = {170, 0, 85}

Related

I am trying to set up my detector for a face recognition project or a program,

but I keep getting this error:
TypeError: an integer is required (got type tuple)
my code is :
def DispID(x, y, w, h, NAME, Image):
Name_y_pos = y - 10
Name_X_pos = x + w / 2 - (len(NAME) * 7 / 2)
if Name_X_pos < 0:
Name_X_pos = 0
elif (Name_X_pos + 10 + (len(NAME) * 7) > Image.shape[1]):
Name_X_pos = Name_X_pos - (Name_X_pos + 10 + (len(NAME) * 7) - (Image.shape[1]))
if Name_y_pos < 0:
Name_y_pos = Name_y_pos = y + h + 10
draw_box(Image, x, y, w, h)
cv2.rectangle(Image, (int(Name_X_pos) - 10, int(Name_y_pos) - 25), (int(Name_X_pos) + 10 + (len(NAME) * 7), int(Name_y_pos) - 1), (0, 0, 0), -2) # Draw a Black Rectangle over the face frame
cv2.rectangle(Image, (Name_X_pos - 10, Name_y_pos - 25), (Name_X_pos + 10 + (int(len(NAME)) * 7), Name_y_pos - 1), WHITE, 1)
cv2.putText(Image, NAME, (Name_X_pos, Name_y_pos - 10), cv2.FONT_HERSHEY_DUPLEX, .4, WHITE)
Error log : cv2.rectangle(Image, (int(Name_X_pos) - 10, int(Name_y_pos) - 25), (int(Name_X_pos) + 10 + (len(NAME) * 7), int(Name_y_pos) - 1), (0, 0, 0), -2) TypeError: an integer is required (got type tuple)
Due to some division made to define Name_X_pos you can have a assume a float number, which is not allowed in the rectangle function.
I know the error was not saying anything about float number, but about tuple. I had to test line by line to find the solution.
That's the modification I made:
<!-- language: python -->
cv2.rectangle(img, (int(Name_X_pos) - 10, int(Name_y_pos) - 25), (int(Name_X_pos) + 10 + (len(NAME) * 7), int(Name_y_pos) - 1), (0, 0, 0), -2) # Draw a Black Rectangle over the face frame
cv2.rectangle(img, (int(Name_X_pos) - 10, Name_y_pos - 25), (int(Name_X_pos) + 10 + int(len(NAME)) * 7, Name_y_pos - 1), WHITE, 1)
cv2.putText(img, NAME, (int(Name_X_pos), Name_y_pos - 10), cv2.FONT_HERSHEY_DUPLEX, .4, WHITE)
Result:

Drawing a line using centroid point in opencv

How do I pass a line through the center of a contour? I have the center coordinates of my contour.
This is how you solve this question -
Original image -
Result image -
You first need to do basic filtering and find the contour. Then -
1) Find out the area of contour (minAreaRect)
2) Extract points from the contour (BoxPoints)
3) Convert it to a numpy array (np.array)
4) Order the points (perspective.order_points)
5) Take out Top-left, Top-right, Bottom-right and Bottom-left(tl, tr, br, bl) = box (Line 52)
6) Calculate the midpoints ( (point1 + point2) / 2)
7) Draw the lines (line 76)
Here is the code for it
# import the necessary packages
from scipy.spatial import distance as dist
from imutils import perspective
from imutils import contours
import numpy as np
import imutils
import cv2
# Method to find the mid point
def midpoint(ptA, ptB):
return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)
# load the image, convert it to grayscale, and blur it slightly
image = cv2.imread("test.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)
# perform edge detection, then perform a dilation + erosion to
# close gaps in between object edges
edged = cv2.Canny(gray, 50, 100)
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)
# find contours in the edge map
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
# loop over the contours individually
for c in cnts:
# This is to ignore that small hair countour which is not big enough
if cv2.contourArea(c) < 1000:
continue
# compute the rotated bounding box of the contour
box = cv2.minAreaRect(c)
box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)
box = np.array(box, dtype="int")
# order the points in the contour such that they appear
# in top-left, top-right, bottom-right, and bottom-left
# order, then draw the outline of the rotated bounding
# box
box = perspective.order_points(box)
# draw the contours on the image
orig = image.copy()
cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 3)
# unpack the ordered bounding box, then compute the midpoint
# between the top-left and top-right coordinates, followed by
# the midpoint between bottom-left and bottom-right coordinates
(tl, tr, br, bl) = box
(tltrX, tltrY) = midpoint(tl, tr)
(blbrX, blbrY) = midpoint(bl, br)
# compute the midpoint between the top-left and top-right points,
# followed by the midpoint between the top-righ and bottom-right
(tlblX, tlblY) = midpoint(tl, bl)
(trbrX, trbrY) = midpoint(tr, br)
# draw and write the midpoints on the image
cv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1)
cv2.putText(orig, "({},{})".format(tltrX, tltrY), (int(tltrX - 50), int(tltrY - 10) - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 2)
cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1)
cv2.putText(orig, "({},{})".format(blbrX, blbrY), (int(blbrX - 50), int(blbrY - 10) - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 2)
cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1)
cv2.putText(orig, "({},{})".format(tlblX, tlblY), (int(tlblX - 50), int(tlblY - 10) - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 2)
cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1)
cv2.putText(orig, "({},{})".format(trbrX, trbrY), (int(trbrX - 50), int(trbrY - 10) - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 2)
# draw lines between the midpoints
cv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)),
(255, 0, 255), 2)
cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)),
(255, 0, 255), 2)
# compute the Euclidean distance between the midpoints
dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))
dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))
# loop over the original points
for (xA, yA) in list(box):
# draw circles corresponding to the current points and
cv2.circle(orig, (int(xA), int(yA)), 5, (0,0,255), -1)
cv2.putText(orig, "({},{})".format(xA, yA), (int(xA - 50), int(yA - 10) - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 2)
# show the output image, resize it as per your requirements
cv2.imshow("Image", orig)
cv2.waitKey(0)

Loop to change spring lengths doesn't change anything when I run it

The project I'm working on is supposed to model a pulse moving down a set of spheres connected by springs. I am trying to decrease the spring length as the pulse moves down the chain, but when I run it, nothing happens.
Here's my code:
from visual import *
one = sphere(pos=(-10,0,0), radius = 0.5, color = color.red)
two = sphere(pos=(-8,0,0), radius = 0.5, color = color.orange)
three = sphere(pos=(-6,0,0), radius = 0.5, color = color.yellow)
four = sphere(pos=(-4,0,0), radius = 0.5, color = color.green)
five = sphere(pos=(-2,0,0), radius = 0.5, color = color.blue)
six = sphere(pos=(0,0,0), radius = 0.5, color = color.cyan)
seven = sphere(pos=(2,0,0), radius = 0.5, color = color.magenta)
eight = sphere(pos=(4,0,0), radius = 0.5, color = color.white)
nine = sphere(pos=(6,0,0), radius = 0.5, color = color.red)
ten = sphere(pos=(8,0,0), radius = 0.5, color = color.orange)
spring1 = helix(pos = (-10, 0, 0), length = 2, radius = 0.3,
thickness = 0.05, color = color.red)
spring2 = helix(pos = (-8, 0, 0), length = 2, radius = 0.3,
thickness = 0.05, color = color.orange)
spring3 = helix(pos = (-6, 0, 0), length = 2, radius = 0.3,
thickness = 0.05, color = color.yellow)
spring4 = helix(pos = (-4, 0, 0), length = 2.0, radius = 0.3,
thickness = 0.05, color = color.green)
spring5 = helix(pos = (-2, 0, 0), length = 2.0, radius = 0.3,
thickness = 0.05, color = color.blue)
spring6 = helix(pos = (0, 0, 0), length = 2.0, radius = 0.3,
thickness = 0.05, color = color.cyan)
spring7 = helix(pos = (2, 0, 0), length = 2.0, radius = 0.3,
thickness = 0.05, color = color.magenta)
spring8 = helix(pos = (4, 0, 0), length = 2.0, radius = 0.3,
thickness = 0.05, color = color.white)
spring9 = helix(pos = (6, 0, 0), length = 2.0, radius = 0.3,
thickness = 0.05, color = color.red)
masses = [one, two, three, four, five, six, seven, eight, nine, ten]
springs = [spring1, spring2, spring3, spring4, spring5, spring6, spring7,
spring8, spring9]
while True:
n=0
deltax=.2
while n < 10:
rate(30)
masses[n].pos.x = masses[n].pos.x + deltax
if n < 9:
springs[n].pos = masses[n].pos
springs[n].axis = masses[n+1].pos-masses[n].pos
n=n+1
n = n-1
while n >= 0:
rate(30)
masses[n].pos.x = masses[n].pos.x - deltax
if n < 0:
springs[n-1].pos = masses[n-1].pos - deltax
springs[n-1].axis = masses[n].pos-masses[n-1].pos
n = n-1
while True:
m=0
deltat=.2
while m<9:
rate(30)
springs[m].length = springs[m].length - deltat
springs[m].length = springs[m].length + deltat
m=m+1
m=m-1
while n>=0:
rate(30)
springs[m].length = springs[m].length - deltat
springs[m].length = springs[m].length + deltat
m=m-1
Make the masses have opacity = 0.3 and replace the first rate statement with scene.waitfor('click'). You'll see that when you move the nth mass to the right, the spring does in fact shorten, and when the (n+1)th mass is moved, the spring to its right shortens, leaving a gap between the nth spring and the (n+1)th spring.
Incidentally, I don't understand where there is a second "while True". It will never be reached.
I'll advertise that a better place to pose VPython questions is in the VPython forum at
https://groups.google.com/forum/?fromgroups&hl=en#!forum/vpython-users

OpenGL ES 3.0 GL_POINTS doesn't render anything

Below is a mininal reproducer:
GL_CHECK(glClearColor(0.4f, 0.4f, 0.4f, 1.0f));
GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT |
GL_STENCIL_BUFFER_BIT));
GL_CHECK(glUseProgram(this->pp_->shader_program));
GL_CHECK(glEnable(GL_TEXTURE_2D));
GL_CHECK(glActiveTexture(GL_TEXTURE0));
GL_CHECK(glBindTexture(GL_TEXTURE_2D, this->particle_->id));
GLfloat points[] = { 150.f, 150.f, 10.0f, 150.0f, 175.0f, 10.0f };
GLfloat colors[] = { 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f };
shader_pass_set_uniform(this->pp_, HASH("mvp"), glm::value_ptr(this->camera_));
GL_CHECK(glEnableVertexAttribArray(0));
GL_CHECK(glEnableVertexAttribArray(3));
GL_CHECK(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, &points[0]));
GL_CHECK(glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 0, &colors[0]));
GL_CHECK(glDrawArrays(GL_POINTS, 0, 2));
vertex shader:
#version 300 es
layout(location = 0) in highp vec3 vertex;
layout(location = 3) in highp vec4 color;
out lowp vec4 vcolor;
uniform mat4 mvp;
void main()
{
vcolor = color;
gl_Position = mvp * vec4(vertex.xy, 0.0, 1.0);
gl_PointSize = vertex.z;
}
fragment shader:
#version 300 es
uniform sampler2D stexture;
in lowp vec4 vcolor;
layout(location = 0) out lowp vec4 ocolor;
void main()
{
ocolor = texture(stexture, gl_PointCoord) * vcolor;
}
Nothing gets rendered on-screen, my glxinfo can be found in this pastebin. When I render the same texture onto a triangle it works.
Here is also the render loop as captured with apitrace:
250155 glClearColor(red = 0.5, green = 0.5, blue = 0.5, alpha = 1)
250157 glClear(mask = GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT)
250159 glUseProgram(program = 9)
250161 glEnable(cap = GL_TEXTURE_2D)
250163 glActiveTexture(texture = GL_TEXTURE0)
250165 glBindTexture(target = GL_TEXTURE_2D, texture = 2)
250167 glUniformMatrix4fv(location = 0, count = 1, transpose = GL_FALSE, value = {0.001953125, 0, 0, 0, 0, 0.002604167, 0, 0, 0, 0, -1, 0, -1, -1, -0, 1})
250168 glEnableVertexAttribArray(index = 0)
250170 glEnableVertexAttribArray(index = 3)
250174 glVertexAttribPointer(index = 0, size = 3, type = GL_FLOAT, normalized = GL_FALSE, stride = 0, pointer = blob(24))
250175 glVertexAttribPointer(index = 3, size = 4, type = GL_FLOAT, normalized = GL_FALSE, stride = 0, pointer = blob(32))
250176 glDrawArrays(mode = GL_POINTS, first = 0, count = 2)
250178 glXSwapBuffers(dpy = 0x1564010, drawable = 50331661)
I guess that could mean, that the range of point sizes, that your GLES implementation supports, may be not what you are expecting. You can try something like:
GLint range[2];
glGetIntegerv(GL_ALIASED_POINT_SIZE_RANGE, range); // for example, (1, 511) in my implementation
to check it out. Any implementation guarantees, that range[1] is at least 1.0. The value gl_PointSize is getting clamped to the range, so in the worst case you won't be able to set point with size, greater than 1. In this case gl_PointCoord seems to evaluate to (1, 0) (according to formula from specs) at the only fragment, that is going to be drawn for each point. After the texture's wrap mode come into play, (1, 0) may turn into (0, 0), for example if you are using GL_REPEAT as the texture's wrap mode. If you'd like to safely draw a point with side, greater than one, you should try using the ordinary way to draw squares (for example using four vertices and GL_TRIANGLE_FAN or GL_TRIANGLE_STRIP mode).

Draw Raphael Donut Chart

http://www.mediafire.com/view/z8ad4pedqr7twbl/donut.png
I want to draw this donut like that image. I have use raphaeljs for draw it. But I can't find the solution to make these borders with red and blue. Can someone help me? Is it possible or not?
My code below:
Raphael.fn.donutChart = function (cx, cy, r, rin, values, labels, stroke) {
var paper = this,
rad = Math.PI / 180,
chart = this.set();
function sector(cx, cy, r, startAngle, endAngle, params) {
//console.log(params.fill);
var x1 = cx + r * Math.cos(-startAngle * rad),
x2 = cx + r * Math.cos(-endAngle * rad),
y1 = cy + r * Math.sin(-startAngle * rad),
y2 = cy + r * Math.sin(-endAngle * rad),
xx1 = cx + rin * Math.cos(-startAngle * rad),
xx2 = cx + rin * Math.cos(-endAngle * rad),
yy1 = cy + rin * Math.sin(-startAngle * rad),
yy2 = cy + rin * Math.sin(-endAngle * rad);
return paper.path(["M", xx1, yy1,
"L", x1, y1,
"A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2,
"L", xx2, yy2,
"A", rin, rin, 0, +(endAngle - startAngle > 180), 1, xx1, yy1, "z"]
).attr(params);
}
var angle = 0,
total = 0,
start = 0,
process = function (j) {
var value = values[j],
angleplus = 360 * value / total,
popangle = angle + (angleplus / 2),
color = Raphael.hsb(start, .75, 1),
ms = 500,
delta = 30,
bcolor = "#ccc",
p = sector(cx, cy, r, angle, angle + angleplus, {fill:"#dfdfdf", "stroke-width":3, stroke:"red"}),
txt = paper.text(cx + (r + delta + 155) * Math.cos(-popangle * rad), cy + (r + delta + 150) * Math.sin(-popangle * rad), labels[j]).attr({fill:"#000", stroke: "none", opacity: 0, "font-size": 20});
p.mouseover(function () {
p.stop().animate({transform: "s1.25 1.25 " + cx + " " + cy}, ms, "elastic");
txt.stop().animate({opacity: 1}, ms, "elastic");
}).mouseout(function () {
p.stop().animate({transform: ""}, ms, "elastic");
txt.stop().animate({opacity: 0}, ms);
});
angle += angleplus;
chart.push(p);
chart.push(txt);
start += .1;
};
for (var i = 0, ii = values.length; i < ii; i++) {
total += values[i];
}
for (i = 0; i < ii; i++) {
process(i);
}
return chart;
};
var values = [],
labels = [];
$("tr").each(function () {
values.push(parseInt($("td", this).text(), 10));
labels.push($("th", this).text());
});
$("table").hide();
Raphael("holder", 700, 700).donutChart(350, 350, 80, 150, values, labels, "#fff");
You have to create separate paths if you want to stroke them differently:
var p = paper.path(["M", xx1, yy1,
"L", x1, y1,
"A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2,
"L", xx2, yy2,
"A", rin, rin, 0, +(endAngle - startAngle > 180), 1, xx1, yy1, "z"]
).attr(params);
paper.path(["M", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2]).attr({stroke: 'blue', 'stroke-width': 3});
paper.path(["M", xx2, yy2, "A", rin, rin, 0, +(endAngle - startAngle > 180), 1, xx1, yy1]).attr({stroke: 'red', 'stroke-width': 3});
return p;

Resources