If I have two coordinates of a point anywhere, how can I find two other points in that line that make up the middle third? - math

Say I have a line coor1: (0,300) coor2: (600,300)
With that, I want to find the 2 middle third points which would be (200,300) (400,300)
Normally, I'd do something like:
x = (xCoor2 - xCoor1) * (1.0/3.0) + xCoor1;
y = yCoor1 - (yCoor1 - yCoor2) * (1.0/3.0);
But that would only work successfully in some cases. I need one statement that can find those 2 points when coor1 and coor2 are anywhere. Such as coor1: (400,400) coor2: (600,600)

Point left{0.0,300.0}, right{600.0,300.0}, one_third, two_thirds;
one_third = left + (right - left) *1.0/3.0;
two_thirds= left + (right - left) *2.0/3.0;
or more explicitly
one_third.x = left.x + (right.x - left.x) *1.0/3.0;
one_third.y = left.y + (right.y - left.y) *1.0/3.0;
two_thirds.x= left.x + (right.x - left.x) *2.0/3.0;
two_thirds.y= left.y + (right.y - left.y) *2.0/3.0;

Related

How to create julia color scheme for displaying Ct scan Makie.jl

I use makie.jl with slicesNumb for visualization of PET/CT scans, I have 3d array of attenuation values and I display heatmap with changing slices using slider - this works well I have two problems
I do not know how to be able to define custom colormaps (basically I need to be able to specify that all above some threshold value will be black and all below white and values between will have grey values proportional to attenuation value).
2)I would like to be able to display to display over my image (tachnically heatmap) another ones where I would be able to controll transparency - alpha value of pixels - in order to display some annotations/ PET ...
code that works but without those 2 functionalities and how it looks
using GLMakie
```#doc
simple display of single image - only in transverse plane
```
function singleCtScanDisplay(arr ::Array{Number, 3})
fig = Figure()
sl_x = Slider(fig[2, 1], range = 1:1:size(arr)[3], startvalue = 40)
ax = Axis(fig[1, 1])
hm = heatmap!(ax, lift(idx-> arr[:,:, floor(idx)], sl_x.value) ,colormap = :grays)
Colorbar(fig[1, 2], hm)
fig
end
Thanks for help !
You can use Colors and ColorSchemeTools, but you will need to add the top and bottom of the scheme according to your thresholds.
using Colors, ColorSchemeTools
truemin = 0
truemax = 600
max_shown_black = 20
min_shown_white = 500
data = rand(truemin:truemax, (500, 500, 20))
grayscheme = [fill(colorant"black", max_shown_black - truemin + 1);
collect(make_colorscheme(identity, identity, identity,
length = min_shown_white - max_shown_black - 1));
fill(colorant"white", truemax - min_shown_white + 1)]
For controlling alpha, I would add a popup window with an alpha slider. Take a look at some of the distributable DICOM tools for examples.
I finally managed it basically I load 3 dimensional data stored in hdf5 (I loaded it into hdf5 from raw using python)
It enables viewing transverse slices and annotate 3d pathes in a mask that will be displayed over main image
exmpleH = #spawnat persistenceWorker Main.h5manag.getExample()
minimumm = -1000
maximumm = 2000
arrr= fetch(exmpleH)
imageDim = size(arrr)
using GLMakie
maskArr = Observable(BitArray(undef, imageDim))
MyImgeViewer.singleCtScanDisplay(arrr, maskArr,minimumm, maximumm)
Now definition of the required modules
```#doc
functions responsible for displaying medical image Data
```
using DrWatson
#quickactivate "Probabilistic medical segmentation"
module MyImgeViewer
using GLMakie
using Makie
#using GeometryBasics
using GeometricalPredicates
using ColorTypes
using Distributed
using GLMakie
using Main.imageViewerHelper
using Main.workerNumbers
## getting id of workers
```#doc
simple display of single image - only in transverse plane we are adding also a mask that
arrr - main 3 dimensional data representing medical image for example in case of CT each voxel represents value of X ray attenuation
minimumm, maximumm - approximately minimum and maximum values we can have in our image
```
function singleCtScanDisplay(arrr ::Array{Number, 3}, maskArr , minimumm, maximumm)
#we modify 2 pixels just in order to make the color range constant so slices will be displayed in the same windows
arrr[1,1,:].= minimumm
arrr[2,1,:].= maximumm
imageDim = size(arrr) # dimenstion of the primary image for example CT scan
slicesNumb =imageDim[3] # number of slices
#defining layout variables
scene, layout = GLMakie.layoutscene(resolution = (600, 400))
ax1 = layout[1, 1] = GLMakie.Axis(scene, backgroundcolor = :transparent)
ax2 = layout[1, 1] = GLMakie.Axis(scene, backgroundcolor = :transparent)
#control widgets
sl_x =layout[2, 1]= GLMakie.Slider(scene, range = 1:1: slicesNumb , startvalue = slicesNumb/2 )
sliderXVal = sl_x.value
#color maps
cmwhite = cgrad(range(RGBA(10,10,10,0.01), stop=RGBA(0,0,255,0.4), length=10000));
greyss = createMedicalImageColorSchemeB(200,-200,maximumm, minimumm )
####heatmaps
#main heatmap that holds for example Ct scan
currentSliceMain = GLMakie.#lift(arrr[:,:, convert(Int32,$sliderXVal)])
hm = GLMakie.heatmap!(ax1, currentSliceMain ,colormap = greyss)
#helper heatmap designed to respond to both changes in slider and changes in the bit matrix
currentSliceMask = GLMakie.#lift($maskArr[:,:, convert(Int32,$sliderXVal)])
hmB = GLMakie.heatmap!(ax1, currentSliceMask ,colormap = cmwhite)
#adding ability to be able to add information to mask where we clicked so in casse of mit matrix we will set the point where we clicked to 1
indicatorC(ax1,imageDim,scene,maskArr,sliderXVal)
#displaying
colorB = layout[1,2]= Colorbar(scene, hm)
GLMakie.translate!(hmB, Vec3f0(0,0,5))
scene
end
```#doc
inspired by https://github.com/JuliaPlots/Makie.jl/issues/810
Generaly thanks to this function the viewer is able to respond to clicking on the slices and records it in the supplied 3 dimensional AbstractArray
ax - Axis which store our heatmap slices which we want to observe wheather user clicked on them and where
dims - dimensions of main image for example CT
sc - Scene where our axis is
maskArr - the 3 dimensional bit array that has exactly the same dimensions as main Array storing image
sliceNumb - represents on what slide we are on currently on - ussually it just give information from slider
```
function indicatorC(ax::Axis,dims::Tuple{Int64, Int64, Int64},sc::Scene,maskArr,sliceNumb::Observable{Any})
register_interaction!(ax, :indicator) do event::GLMakie.MouseEvent, axis
if event.type === MouseEventTypes.leftclick
println("clicked")
##async begin
#appropriately modyfing wanted pixels in mask array
#async calculateMouseAndSetmaskWrap(maskArr, event,sc,dims,sliceNumb)
#
#
# println("fetched" + fetch(maskA))
# finalize(maskA)
#end
return true
#print("xMouse: $(xMouse) yMouse: $(yMouse) compBoxWidth: $(compBoxWidth) compBoxHeight: $(compBoxHeight) calculatedXpixel: $(calculatedXpixel) calculatedYpixel: $(calculatedYpixel) pixelsNumbInX $(pixelsNumbInX) ")
end
end
end
```#doc
wrapper for calculateMouseAndSetmask - from imageViewerHelper module
given mouse event modifies mask accordingly
maskArr - the 3 dimensional bit array that has exactly the same dimensions as main Array storing image
event - mouse event passed from Makie
sc - scene we are using in Makie
```
function calculateMouseAndSetmaskWrap(maskArr, event,sc,dims,sliceNumb)
maskArr[] = calculateMouseAndSetmask(maskArr, event,sc,dims,sliceNumb)
end
end #module
and helper methods
```#doc
functions responsible for helping in image viewer - those functions are meant to be invoked on separate process
- in parallel
```
using DrWatson
#quickactivate "Probabilistic medical segmentation"
module imageViewerHelper
using Documenter
using ColorTypes
using Colors, ColorSchemeTools
using Makie
export calculateMouseAndSetmask
export createMedicalImageColorSchemeB
# using AbstractPlotting
```#doc
given mouse event modifies mask accordingly
maskArr - the 3 dimensional bit array that has exactly the same dimensions as main Array storing image
event - mouse event passed from Makie
sc - scene we are using in Makie
```
function calculateMouseAndSetmask(maskArr, event,sc,dims,sliceNumb)
#position from top left corner
xMouse= Makie.to_world(sc,event.data)[1]
yMouse= Makie.to_world(sc,event.data)[2]
#data about height and width in layout
compBoxWidth = 510
compBoxHeight = 510
#image dimensions - number of pixels from medical image for example ct scan
pixelsNumbInX =dims[1]
pixelsNumbInY =dims[2]
#calculating over which image pixel we are
calculatedXpixel =convert(Int32, round( (xMouse/compBoxWidth)*pixelsNumbInX) )
calculatedYpixel = convert(Int32,round( (yMouse/compBoxHeight)*pixelsNumbInY ))
sliceNumbConv =convert(Int32,round( sliceNumb[] ))
#appropriately modyfing wanted pixels in mask array
return markMaskArrayPatch( maskArr ,CartesianIndex(calculatedXpixel, calculatedYpixel, sliceNumbConv ),2)
end
```#doc
maskArr - the 3 dimensional bit array that has exactly the same dimensions as main Array storing image
point - cartesian coordinates of point around which we want to modify the 3 dimensional array from 0 to 1
```
function markMaskArrayPatch(maskArr, pointCart::CartesianIndex{3}, patchSize ::Int64)
ones = CartesianIndex(patchSize,patchSize,patchSize) # cartesian 3 dimensional index used for calculations to get range of the cartesian indicis to analyze
maskArrB = maskArr[]
for J in (pointCart-ones):(pointCart+ones)
diff = J - pointCart # diffrence between dimensions relative to point of origin
if cartesianTolinear(diff) <= patchSize
maskArrB[J]=1
end
end
return maskArrB
end
```#doc
works only for 3d cartesian coordinates
cart - cartesian coordinates of point where we will add the dimensions ...
```
function cartesianTolinear(pointCart::CartesianIndex{3}) :: Int16
abs(pointCart[1])+ abs(pointCart[2])+abs(pointCart[3])
end
```#doc
creating grey scheme colors for proper display of medical image mainly CT scan
min_shown_white - max_shown_black range over which the gradint of greys will be shown
truemax - truemin the range of values in the image for which we are creating the scale
```
#taken from https://stackoverflow.com/questions/67727977/how-to-create-julia-color-scheme-for-displaying-ct-scan-makie-jl/67756158#67756158
function createMedicalImageColorSchemeB(min_shown_white,max_shown_black,truemax,truemin ) ::Vector{Any}
# println("max_shown_black - truemin + 1")
# println(max_shown_black - truemin + 1)
# println(" min_shown_white - max_shown_black - 1")
# println( min_shown_white - max_shown_black - 1)
# println("truemax - min_shown_white + 1")
# println(truemax - min_shown_white + 1)
return [fill(colorant"black", max_shown_black - truemin + 1);
collect(make_colorscheme(identity, identity, identity,
length = min_shown_white - max_shown_black - 1));
fill(colorant"white", truemax - min_shown_white + 1)]
end
end #module

How to align Gridspace plots in holoviews Layout?

I have trouble understanding how the holoviews Layout works if it contains Gridspace components. In the example below I have 2 simple plots that are returned as Gridspace. While they display just fine, I'd like to align them on the right edge. According to the docs, that should be done by passing align='end' option to the respective component(s) in the Layout - however this will result in ValueError: Unexpected option 'align' for GridSpace type across all extensions. No similar options found. error.
df = pd.DataFrame()
df['x'] = np.arange(100)
df['y'] = df['x']*10
df['c1'] = [1] * 25 + [2] * 25 + [3] * 25 + [4] * 25
df['c2'] = [1] * 50 + [2] * 50
p1 = df.hvplot(x='x', y='y', datashade=False, row='c1')
p2 = df.hvplot(x='x', y='y', datashade=False, row='c2')
(p1.opts(align='end') + p2).cols(1)
This will work fine without the .opts(align='end) other than the alignment being on the left: plot without align
It would be great if someone knows whether this is a limitation of Gridspaces or I was just using the wrong options.

Python3: Produce a patern with stars and must use a 2 dimensional list

Python3.6: I have an assignment for which I need to produce a patern with stars and must use a 2 dimensional list.
The first part was merely using the print() with concatenation.
def corners():
"""This function will display a Stars in the top left
and bottom right corners"""
a4 = '****'
a3 = '***'
a2 = '**'
a1 = '*'
s3 = ' '
s4 = ' '
s5 = ' '
print(a4 + s3)
print(a3 + s4)
print(a2 + s5)
print(a1 + s5 + a1)
print(s5 + a2)
print(s4 + a3)
print(s3 + a4)
corners()
(image displayed looks like this)
****
***
**
* *
**
***
****
Now, the second part is to do the same thing, but use a 2 dimensional list along with loops. I have tried, and I am stuck. The assignment has a total of 5 different parterns. If anyone would be so kind as to provide some assistant to figure one of them out, then the other 4 should be easier.
Thanks.
Let's begin with the concrete case that matches your original static solution. Assume user input is 7. Your task is then to print 7 lines. Each line consists of 7 characters:
4 stars, 3 spaces, no stars
3 stars, 4 spaces, no stars
2 stars, 5 spaces, no stars
1 star, 5 spaces, 1 star
... then the same in reverse.
So, the first element of your list is [4,3,0], then [3,4,0] and so on.
The full 2-dimensional list will be [[4,3,0], [3,4,0], ... etc]
Call your list rows:
rows = [[4,3,0], [3,4,0], ... etc]
Now if you do this:
for (l_stars, spaces, r_stars) in rows:
the first time around, l_stars will be 4, spaces will be 3, and r_stars will be zero. Inside the for loop, print the appropriate number of stars and spaces:
for (l_stars, spaces, r_stars) in rows:
print("*" * l_stars, " " * spaces, "*" * r_stars, sep="")
If l_stars has the value 4, then "*" * l_stars will be "****", and so on. The sep in the print statement is to stop print putting extra spaces where the commas are.
Now you see the value of using a 2-dimensional list. Your program is reduced from 14 statements to 3 and the pattern is much easier to change. The ability to change the pattern is needed if the program is to respond to user input. I must say that makes this a very challenging task for a beginner.
In the general case your task is to print n lines. Each line consists of n characters:
n-3 stars, n-4 spaces, no stars
n-4 stars, n-3 spaces, no stars
n-5 stars, n-2 spaces, no stars
... and so on down to
1 star, n-2 spaces, 1 star
... then the same in reverse.
The number of rows to print is variable: you need n rows. One way to do this is with a list comprehension. If the user's input is n, that will be something like
rows = [ [...something...] for i in range(n) ]
The tricky part here is that your pattern is constant in the middle:
* *
so rows consists of 3 parts: top-left corner, middle, bottom-right corner, and grows or shrinks upwards and downwards from the middle. So you have to build it up as 3 parts. It's not clear from your description what you want to happen if n is an even number. I'll assume you want two copies of the same middle row in that case.
try:
n = int(input("Enter size of pattern:"))
except:
print("Invalid input, using 7")
n = 7
top_left = [[n-i, i, 0] for i in range (3,n-1)]
middle = [[1,n-2,1]]
if not n % 2: # n is even, need two copies
middle *= 2
bottom_right = [[0, i, n-i] for i in range (n-2,2,-1)]
rows = top_left + middle + bottom_right
for (l_stars, spaces, r_stars) in rows:
print("*" * l_stars, " " * spaces, "*" * r_stars, sep="")
I'll leave it up to you to do any range checking on the input that is required.

How to create an rectangle in a 3d area via vector&angle

I have a 3d game where I will create an rectangle which is working as screen and the game itself works with vectors to positions. so I will create an rectangle and have only these parameters aviable:
start position ->vector (x,y,z).
Angle(rotation) of object(x,y,z).
size of rectangle.
now also the object need to be roatet to the right side so they are using angels also (x,y,z).
example:
position:-381.968750 -28.653845 -12702.185547
angle: -0.000 90.000 90.000
What I will create is an little bit hard but as idea simple.
I choose 2 complete different positions and angles and will create from the first vector to the second an rectangle.
I can only create an rectangle with the start point and angle.
and I can set the size so (x,y)
So I will now insert 2 positions(vectors) with 2 different angles
The rectangle will have the middle value between the first and second angle so like (90 and 0) -> 45
And the rectangle will start at the start vector and will end with his own size so I don't have a chance to use the end vector directly.
Legendary on photo:
Green=>start and end positions(vectors).
red => the marked zone.
Blue => how I will have the rectangle.
aem_point = vgui.Create( "AEM.Main.Panel" )
if IsValid(aem_point) then
aem_point:SetSize( 2,2 ) -- <-the size that i can set
aem_point:SetPos( 0, 0 )
aem_ph = vgui.Create( "DHTML", aem_point )
aem_ph:SetSize( aem_point:GetSize() )
aem_ph:SetPos(aem_point:GetPos())
aem_ph:SetVisible( true )
aem_ph:SetHTML([[
<html>
<body style="margin:0px;padding:0px;font-size:20px;color:red;border-style: solid;border-color: #ff0000;background-color:rgba(255,0,0,0.1);">
</body>
</html>
]] )
end
hook.Add( "PostDrawOpaqueRenderables", "DrawSample3D2DFrame" .. math.random(), function()
if first and dat_finish then
vgui.Start3D2D( input_position, input_angle, 1 ) -- <-and position&vec
aem_point:Paint3D2D()
vgui.End3D2D()
end
end )
Oh so you want to create a 3d2d plane from 2 vector positions?
Vec1 = A
Vec2 = B
input_position = ( Vec1 + Vec2 ) / 2
A problem you will run into is you need 3 points to generate a plane, so while you can get the position of the screen to get the angle of it you will need another point.
If these screens of yours are staticly set, as in you put their position into the lua code manually and dont intend to have it move or anything, just manually putting in the angle is by far the most simple approch.
As you can see, both of these planes are on the same two points, but they have diffrent angles.
I wrote the demo in expression 2, this should make it clear as to how this works, if you have any other questions just ask.
A = entity(73):pos()
B = entity(83):pos()
if(first())
{
holoCreate(1)
holoCreate(2)
}
holoPos(1,(A+B)/2)
holoScaleUnits(1,vec( abs(B:y() - A:y()) , 1 , abs(sqrt( ( B:z() - A:z() ) ^ 2 + ( B:x() - A:x() ) ^ 2 ))))
holoAng(1,ang(0,90,45))
holoPos(2,(A+B)/2)
holoScaleUnits(2,vec( abs(sqrt( ( B:x() - A:x() ) ^ 2 + ( B:y() - A:y() ) ^ 2 )) , 1 , abs(B:z()-A:z())))
holoAng(2,ang(0,45,0))

Find specific point between 2 points - three.js

How can I find a point ( C (x,y,z) ) between 2 points ( A(x,y,z) , B(x,y,z) ) in a thgree.js scene?
I know that with this: mid point I can find the middle point between them, but I don't want the middle point, I want to find the point which is between them and also has distance a from the A point?
in this picture you can see what I mean :
Thank you.
Basically you need to get the direction vector between the two points (D), normalize it, and you'll use it for getting the new point in the way: NewPoint = PointA + D*Length.
You could use length normalized (0..1) or as an absolute value from 0 to length of the direction vector.
Here you can see some examples using both methods:
Using absolute value:
function getPointInBetweenByLen(pointA, pointB, length) {
var dir = pointB.clone().sub(pointA).normalize().multiplyScalar(length);
return pointA.clone().add(dir);
}
And to use with percentage (0..1)
function getPointInBetweenByPerc(pointA, pointB, percentage) {
var dir = pointB.clone().sub(pointA);
var len = dir.length();
dir = dir.normalize().multiplyScalar(len*percentage);
return pointA.clone().add(dir);
}
See it in action: http://jsfiddle.net/8mnqjsge/
Hope it helps.
I know the question is for THREE.JS and I end up looking for something similar in Babylon JS.
Just in case if you are using Babylon JS Vector3 then the formula would translate to:
function getPointInBetweenByPerc(pointA, pointB, percentage) {
var dir = pointB.clone().subtract(pointA);
var length = dir.length();
dir = dir.normalize().scale(length *percentage);
return pointA.clone().add(dir);
}
Hope it help somebody.
This is known as lerp between two points
e.g. in Three:
C = new Three.Vector3()
C.lerpVectors(A, B, a)
also in generic this is just a single lerp (linear interpolation) math (basically (a * t) + b * (1 - t)) on each axis. Lerp can be described as follows:
function lerp (a, b, t) {
return a + t * (b - a)
}
in your case (see above) :
A = {
x: lerp(A.x, B.x, a),
y: lerp(A.y, B.y, a),
z: lerp(A.z, B.z, a)
}

Resources