Here are the examples of the csharp api System.Collections.Generic.List.IndexOf(float) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
28 Examples
19
Source : OCR.cs
with GNU General Public License v3.0
from BLinssen
with GNU General Public License v3.0
from BLinssen
public static async Task<string> ImageCorrelation(Bitmap image)
{
List<float> similaritiesWhite = new List<float>();
List<float> similaritiesBlack = new List<float>();
string[] FilePaths = Directory.GetFiles(Path.Combine(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), @"Dataset"));
foreach (string filePath in FilePaths)
{
float similarWhite = 0;
float similarBlack = 0;
Bitmap datasetImage = new Bitmap(filePath);
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
System.Drawing.Color pixel1 = image.GetPixel(x, y);
System.Drawing.Color pixel2 = datasetImage.GetPixel(x, y);
//If there is a white pixel in the same position on both images add a point of similarity
if ((pixel1.R == 255 && pixel1.G == 255 && pixel1.B == 255 && pixel1.A == 255) && (pixel2.R == 255 && pixel2.G == 255 && pixel2.B == 255 && pixel2.A == 255))
{
similarWhite += 1;
}
if ((pixel1.R < 35 && pixel1.G < 35 && pixel1.B < 35 && pixel1.A == 255) && (pixel2.R < 35 && pixel2.G < 35 && pixel2.B < 35 && pixel2.A == 255) && y < 26)
{
similarBlack += 1;
}
}
}
similaritiesWhite.Add(similarWhite);
similaritiesBlack.Add(similarBlack);
}
//If there are less than 30 pixels equal we replacedume there is no Tem found.
if (similaritiesWhite.Max() < 30 || similaritiesBlack.Max() < 30)
return "";
else
{
int WhiteIndex = similaritiesWhite.IndexOf(similaritiesWhite.Max());
int BlackIndex = similaritiesBlack.IndexOf(similaritiesBlack.Max());
if (WhiteIndex == BlackIndex)
{
return Path.GetFileNameWithoutExtension(FilePaths[WhiteIndex]);
}
else
return "";
}
}
19
Source : YoloV3Prediction.cs
with MIT License
from BobLd
with MIT License
from BobLd
public IReadOnlyList<YoloV3Result> GetResults(string[] categories, float confThres = 0.5f, float iouThres = 0.5f)
{
if (BBoxes.Length != yoloV3BboxPredictionCount * 4)
{
throw new ArgumentException($"Bounding box prediction size is not correct. Expected {yoloV3BboxPredictionCount * 4}, got {BBoxes.Length}.", nameof(BBoxes));
}
if (Clreplacedes.Length != yoloV3BboxPredictionCount * categories.Length)
{
throw new ArgumentException($"Clreplacedes prediction size is not correct. Expected {yoloV3BboxPredictionCount * categories.Length}, got {Clreplacedes.Length}. You might want to check the {nameof(categories)}.", nameof(Clreplacedes));
}
// compute scale and pad factors
float heightScale = 1f;
float widthScale = 1f;
float heightPad = 0f;
float widthPad = 0f;
if (ImageWidth < ImageHeight)
{
widthScale = ImageHeight / ImageWidth;
widthPad = ImageWidth * (1 - widthScale) / 2f;
}
else if (ImageWidth > ImageHeight)
{
heightScale = ImageWidth / ImageHeight;
heightPad = ImageHeight * (1 - heightScale) / 2f;
}
// process raw results
List<float[]> results = new List<float[]>();
for (int r = 0; r < yoloV3BboxPredictionCount; r++)
{
var scores = Clreplacedes.Skip(r * categories.Length).Take(categories.Length);
// get the clreplaced' max confidence
var conf = scores.Max();
if (conf < confThres)
{
continue; // if below conf threshold, skip it
}
var bboxAdj = Xywh2xyxy(BBoxes.Skip(r * 4).Take(4).ToArray());
//[x1, y1, x2, y2, conf, c_0, c_1, ...]
results.Add(bboxAdj.Concat(new[] { conf }).Concat(scores).ToArray());
}
// Non-maximum Suppression
results = results.OrderByDescending(x => x[4]).ToList(); // sort by confidence
List<YoloV3Result> resultsNms = new List<YoloV3Result>();
int f = 0;
while (f < results.Count)
{
var res = results[f];
if (res == null)
{
f++;
continue;
}
var conf = res[4];
var clreplacedes_int = res.Skip(5).ToList().IndexOf(conf);
string label = clreplacedes_int > -1 ? categories[clreplacedes_int] : "unknown";
resultsNms.Add(new YoloV3Result(scaleCoords(res.Take(4).ToArray(), ImageHeight, ImageWidth, heightScale, widthScale, heightPad, widthPad), label, conf));
results[f] = null;
var iou = results.Select(bbox => bbox == null ? float.NaN : BoxIoU(res, bbox)).ToList();
for (int i = 0; i < iou.Count; i++)
{
if (float.IsNaN(iou[i])) continue;
if (iou[i] > iouThres)
{
results[i] = null;
}
}
f++;
}
return resultsNms;
}
19
Source : YoloV4Prediction.cs
with MIT License
from BobLd
with MIT License
from BobLd
public IReadOnlyList<YoloV4Result> GetResults(string[] categories, float scoreThres = 0.5f, float iouThres = 0.5f)
{
List<float[]> postProcesssedResults = new List<float[]>();
int clreplacedesCount = categories.Length;
var results = new[] { Idenreplacedy, Idenreplacedy1, Idenreplacedy2 };
for (int i = 0; i < results.Length; i++)
{
var pred = results[i];
var outputSize = shapes[i];
for (int boxY = 0; boxY < outputSize; boxY++)
{
for (int boxX = 0; boxX < outputSize; boxX++)
{
for (int a = 0; a < anchorsCount; a++)
{
var offset = (boxY * outputSize * (clreplacedesCount + 5) * anchorsCount) + (boxX * (clreplacedesCount + 5) * anchorsCount) + a * (clreplacedesCount + 5);
var predBbox = pred.Skip(offset).Take(clreplacedesCount + 5).ToArray();
// ported from https://github.com/onnx/models/tree/master/vision/object_detection_segmentation/yolov4#postprocessing-steps
// postprocess_bbbox()
var predXywh = predBbox.Take(4).ToArray();
var predConf = predBbox[4];
var predProb = predBbox.Skip(5).ToArray();
var rawDx = predXywh[0];
var rawDy = predXywh[1];
var rawDw = predXywh[2];
var rawDh = predXywh[3];
float predX = ((Sigmoid(rawDx) * XYSCALE[i]) - 0.5f * (XYSCALE[i] - 1) + boxX) * STRIDES[i];
float predY = ((Sigmoid(rawDy) * XYSCALE[i]) - 0.5f * (XYSCALE[i] - 1) + boxY) * STRIDES[i];
float predW = (float)Math.Exp(rawDw) * ANCHORS[i][a][0];
float predH = (float)Math.Exp(rawDh) * ANCHORS[i][a][1];
// postprocess_boxes
// (1) (x, y, w, h) --> (xmin, ymin, xmax, ymax)
float predX1 = predX - predW * 0.5f;
float predY1 = predY - predH * 0.5f;
float predX2 = predX + predW * 0.5f;
float predY2 = predY + predH * 0.5f;
// (2) (xmin, ymin, xmax, ymax) -> (xmin_org, ymin_org, xmax_org, ymax_org)
float org_h = ImageHeight;
float org_w = ImageWidth;
float inputSize = 416f;
float resizeRatio = Math.Min(inputSize / org_w, inputSize / org_h);
float dw = (inputSize - resizeRatio * org_w) / 2f;
float dh = (inputSize - resizeRatio * org_h) / 2f;
var orgX1 = 1f * (predX1 - dw) / resizeRatio; // left
var orgX2 = 1f * (predX2 - dw) / resizeRatio; // right
var orgY1 = 1f * (predY1 - dh) / resizeRatio; // top
var orgY2 = 1f * (predY2 - dh) / resizeRatio; // bottom
// (3) clip some boxes that are out of range
orgX1 = Math.Max(orgX1, 0);
orgY1 = Math.Max(orgY1, 0);
orgX2 = Math.Min(orgX2, org_w - 1);
orgY2 = Math.Min(orgY2, org_h - 1);
if (orgX1 > orgX2 || orgY1 > orgY2) continue; // invalid_mask
// (4) discard some invalid boxes
// TODO
// (5) discard some boxes with low scores
var scores = predProb.Select(p => p * predConf).ToList();
float scoreMaxCat = scores.Max();
if (scoreMaxCat > scoreThres)
{
postProcesssedResults.Add(new float[] { orgX1, orgY1, orgX2, orgY2, scoreMaxCat, scores.IndexOf(scoreMaxCat) });
}
}
}
}
}
// Non-maximum Suppression
postProcesssedResults = postProcesssedResults.OrderByDescending(x => x[4]).ToList(); // sort by confidence
List<YoloV4Result> resultsNms = new List<YoloV4Result>();
int f = 0;
while (f < postProcesssedResults.Count)
{
var res = postProcesssedResults[f];
if (res == null)
{
f++;
continue;
}
var conf = res[4];
string label = categories[(int)res[5]];
resultsNms.Add(new YoloV4Result(res.Take(4).ToArray(), label, conf));
postProcesssedResults[f] = null;
var iou = postProcesssedResults.Select(bbox => bbox == null ? float.NaN : BoxIoU(res, bbox)).ToList();
for (int i = 0; i < iou.Count; i++)
{
if (float.IsNaN(iou[i])) continue;
if (iou[i] > iouThres)
{
postProcesssedResults[i] = null;
}
}
f++;
}
return resultsNms;
}
19
Source : Matrix3x3.cs
with MIT License
from chstetco
with MIT License
from chstetco
private Vector3[] Eigenvectors(float[] eigenvalues_unsorted)
{
float[] eigenvalues = (float[])eigenvalues_unsorted.Clone();
System.Array.Sort(eigenvalues);
Vector3 eigenvector0 = GetEigenvector0(eigenvalues);
Vector3 eigenvector1 = GetEigenvector1(eigenvalues, eigenvector0);
Vector3 eigenvector2 = GetEigenvector2(eigenvalues, eigenvector0, eigenvector1);
List<float> values = new List<float> { eigenvalues[0], eigenvalues[1], eigenvalues[2] };
List<float[]> vectors = new List<float[]>(){
new float[] { eigenvector0[0], eigenvector0[1], eigenvector0[2] },
new float[] { eigenvector1[0], eigenvector1[1], eigenvector1[2] },
new float[] { eigenvector2[0], eigenvector2[1], eigenvector2[2] }
};
List<float> values_unsorted = new List<float>();
List<float[]> vectors_unsorted = new List<float[]>();
for (int i = 0; i < 3; i++)
{
int idx = values.IndexOf(eigenvalues_unsorted[i]);
values_unsorted.Add(values[idx]);
vectors_unsorted.Add(vectors[idx]);
values.RemoveAt(idx);
vectors.RemoveAt(idx);
}
return new Vector3[] { new Vector3(vectors_unsorted[0][0], vectors_unsorted[0][1], vectors_unsorted[0][2]),
new Vector3(vectors_unsorted[1][0], vectors_unsorted[1][1], vectors_unsorted[1][2]),
new Vector3(vectors_unsorted[2][0], vectors_unsorted[2][1], vectors_unsorted[2][2]) };
}
19
Source : NeighbourOperator.cs
with GNU General Public License v3.0
from GeoSOSDevelopers
with GNU General Public License v3.0
from GeoSOSDevelopers
public float[] GetNeighbourCount(float[,] data, int rowIndex, int columnIndex, int windowSize,
int rowCount, int columnCount, int landuseTypesCount, List<float> landuseTypeValue)
{
int neighbourLength = (windowSize - 1) / 2;
float[,] tempValue = new float[windowSize, windowSize];
float[] counts = new float[landuseTypesCount];
try
{
for (int i = rowIndex - neighbourLength; i <= rowIndex + neighbourLength; i++)
{
for (int j = columnIndex - neighbourLength; j <= columnIndex + neighbourLength; j++)
{
if (i < 0 || j < 0 || i >= rowCount || j >= columnCount)
{
tempValue[i - rowIndex + neighbourLength, j - columnIndex + neighbourLength] = -1f;
continue;
}
//System.Diagnostics.Debug.WriteLine(data[i, j]);
tempValue[i - rowIndex + neighbourLength, j - columnIndex + neighbourLength] = data[i, j];
}
}
for (int k = 0; k < windowSize; k++)
{
for (int z = 0; z < windowSize; z++)
{
int index = landuseTypeValue.IndexOf(tempValue[k, z]);
if (index != -1)
counts[index]++;
}
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
return counts;
}
19
Source : NeighbourOperator.cs
with GNU General Public License v3.0
from GeoSOSDevelopers
with GNU General Public License v3.0
from GeoSOSDevelopers
public float[,] GetNeighbourData(float[,] data, int windowSize,int rowCount, int columnCount,List<float> urbanTypeValue)
{
float[,] neighbourData = new float[rowCount, columnCount];
int neighbourLength = (windowSize - 1) / 2;
float[,] tempValue = new float[windowSize, windowSize];
int urbanCount = 0;
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
{
for (int columnIndex = 0; columnIndex < columnCount; columnIndex++)
{
for (int i = rowIndex - neighbourLength; i <= rowIndex + neighbourLength; i++)
{
for (int j = columnIndex - neighbourLength; j <= columnIndex + neighbourLength; j++)
{
if (i < 0 || j < 0 || i >= rowCount || j >= columnCount)
{
tempValue[i - rowIndex + neighbourLength, j - columnIndex + neighbourLength] = -1f;
continue;
}
tempValue[i - rowIndex + neighbourLength, j - columnIndex + neighbourLength] = data[i, j];
//System.Diagnostics.Debug.WriteLine(data[i, j]);
}
}
urbanCount = 0;
for (int k = 0; k < windowSize; k++)
{
for (int z = 0; z < windowSize; z++)
{
int index = urbanTypeValue.IndexOf(tempValue[k, z]);
if (index != -1)
urbanCount++;
}
}
neighbourData[rowIndex, columnIndex] = urbanCount;
}
}
return neighbourData;
}
19
Source : GeneralOpertor.cs
with GNU General Public License v3.0
from GeoSOSDevelopers
with GNU General Public License v3.0
from GeoSOSDevelopers
public static int GetNeighbors(int rowIndex, int columnIndex, float[,] cells, int rowCount, int columnCount, int neiWindowSize, List<float> urbanTypeValue)
{
int neighbourLength = (neiWindowSize - 1) / 2;
float[,] tempValue = new float[neiWindowSize, neiWindowSize];
int urbanCount = 0;
for (int i = rowIndex - neighbourLength; i <= rowIndex + neighbourLength; i++)
{
for (int j = columnIndex - neighbourLength; j <= columnIndex + neighbourLength; j++)
{
if (i < 0 || j < 0 || i >= rowCount || j >= columnCount)
{
tempValue[i - rowIndex + neighbourLength, j - columnIndex + neighbourLength] = -1f;
continue;
}
tempValue[i - rowIndex + neighbourLength, j - columnIndex + neighbourLength] = cells[i, j];
//System.Diagnostics.Debug.WriteLine(cells[i, j]);
int index = urbanTypeValue.IndexOf(tempValue[i - rowIndex + neighbourLength, j - columnIndex + neighbourLength]);
if (index != -1)
urbanCount++;
}
}
return urbanCount;
}
19
Source : VoipRange.cs
with MIT License
from GroovyGiantPanda
with MIT License
from GroovyGiantPanda
static public Task OnTick()
{
if (ControlHelper.IsControlJustPressed(Settings.Controls["VoipRange.Toggle"]))
{
currentRange = voipRange.ElementAt((voipRange.Keys.ToList().IndexOf(currentRange.Key) + 1) % (voipRange.Count - 1));
BaseScript.TriggerEvent("Chat.Message", "", "#AAFF99", $"VOIP range set to {currentRange.Value}.");
Function.Call(Hash.NETWORK_SET_TALKER_PROXIMITY, currentRange.Key);
}
if( !CinematicMode.DoHideHud ) {
System.Drawing.Color colorInactive = System.Drawing.Color.FromArgb( 200, 200, 200, 200 );
System.Drawing.Color colorActive = System.Drawing.Color.FromArgb( 255, 138, 201, 38 );
Roleplay.Client.UI.DrawText( $"Range: {currentRange.Value}", new Vector2( 0.18f, 0.95f ), ControlHelper.IsControlPressed( Control.PushToTalk, false, Enums.Controls.ControlModifier.Any ) ? colorActive : colorInactive, 0.25f, 0, false );
}
return Task.FromResult(0);
}
19
Source : VolumeLevelConverter.cs
with GNU General Public License v3.0
from janbert
with GNU General Public License v3.0
from janbert
public static int GetVolumeStep(float volumeNormalized)
{
return Instance.mVolumes.ToList().IndexOf(volumeNormalized);
}
19
Source : SpriteMeshCache.cs
with MIT License
from Juan-Cartes
with MIT License
from Juan-Cartes
BoneWeight CreateBoneWeightFromWeights(List<float> weights)
{
BoneWeight boneWeight = new BoneWeight();
float weight = 0f;
int index = -1;
weight = weights.Max();
if(weight < 0.01f) weight = 0f;
index = weight > 0f? weights.IndexOf(weight) : -1;
boneWeight.weight0 = weight;
boneWeight.boneIndex0 = index;
if(index >= 0) weights[index] = 0f;
weight = weights.Max();
if(weight < 0.01f) weight = 0f;
index = weight > 0f? weights.IndexOf(weight) : -1;
boneWeight.weight1 = weight;
boneWeight.boneIndex1 = index;
if(index >= 0) weights[index] = 0f;
weight = weights.Max();
if(weight < 0.01f) weight = 0f;
index = weight > 0f? weights.IndexOf(weight) : -1;
boneWeight.weight2 = weight;
boneWeight.boneIndex2 = index;
if(index >= 0) weights[index] = 0f;
weight = weights.Max();
if(weight < 0.01f) weight = 0f;
index = weight > 0f? weights.IndexOf(weight) : -1;
boneWeight.weight3 = weight;
boneWeight.boneIndex3 = index;
float sum = boneWeight.weight0 +
boneWeight.weight1 +
boneWeight.weight2 +
boneWeight.weight3;
if(sum > 0f)
{
boneWeight.weight0 /= sum;
boneWeight.weight1 /= sum;
boneWeight.weight2 /= sum;
boneWeight.weight3 /= sum;
}
return boneWeight;
}
19
Source : STVertex.cs
with MIT License
from KillzXGaming
with MIT License
from KillzXGaming
public void SortBoneIndices()
{
BoneIndices.Sort();
if (BoneWeights.Count == BoneIndices.Count)
BoneWeights = BoneWeights.OrderBy(x => BoneIndices[BoneWeights.IndexOf(x)]).ToList();
}
19
Source : AssimpSaver.cs
with GNU General Public License v3.0
from KillzXGaming
with GNU General Public License v3.0
from KillzXGaming
private void WriteVertexWeightsToStream(Mesh mesh, StreamWriter writer)
{
List<float> weights = new List<float>();
Dictionary<int, RiggedWeight> vertIDWeights = new Dictionary<int, RiggedWeight>();
foreach (Bone bone in mesh.Bones)
{
foreach (VertexWeight weight in bone.VertexWeights)
{
weights.Add(weight.Weight);
if (!vertIDWeights.ContainsKey(weight.VertexID))
vertIDWeights.Add(weight.VertexID, new RiggedWeight());
vertIDWeights[weight.VertexID].AddWeight(weight.Weight, mesh.Bones.IndexOf(bone));
}
}
writer.WriteLine($" <vertex_weights count=\"{ vertIDWeights.Count }\">");
writer.WriteLine($" <input semantic=\"JOINT\" source=\"#{ mesh.Name }-skin-joints-array\" offset=\"0\"></input>");
writer.WriteLine($" <input semantic=\"WEIGHT\" source=\"#{ mesh.Name }-skin-weights-array\" offset=\"1\"></input>");
writer.WriteLine(" <vcount>");
writer.Write(" ");
for (int i = 0; i < vertIDWeights.Count; i++)
writer.Write($"{ vertIDWeights[i].WeightCount } ");
writer.WriteLine("\n </vcount>");
writer.WriteLine(" <v>");
writer.Write(" ");
for (int i = 0; i < vertIDWeights.Count; i++)
{
RiggedWeight curWeight = vertIDWeights[i];
for (int j = 0; j < curWeight.WeightCount; j++)
{
writer.Write($"{ curWeight.BoneIndices[j] } { weights.IndexOf(curWeight.Weights[j]) } ");
}
}
writer.WriteLine("\n </v>");
writer.WriteLine($" </vertex_weights>");
}
19
Source : Collision.cs
with Apache License 2.0
from leiurayer
with Apache License 2.0
from leiurayer
public Tuple<int, float> Detect(Display display)
{
List<float> beyonds = new List<float>();
for (int i = 0; i < leaves.Count; i++)
{
float beyond = display.Danmaku.Start - leaves[i];
// 某一行有足够空间,直接返回行号和 0 偏移
if (beyond >= 0)
{
return Tuple.Create(i, 0f);
}
beyonds.Add(beyond);
}
// 所有行都没有空间了,那么找出哪一行能在最短时间内让出空间
float soon = beyonds.Max();
int lineIndex = beyonds.IndexOf(soon);
float offset = -soon;
return Tuple.Create(lineIndex, offset);
}
19
Source : Classification.cs
with MIT License
from MatthewHallberg
with MIT License
from MatthewHallberg
void RunModel() {
//preplaced in input tensor
var runner = session.GetRunner();
runner.AddInput(graph[INPUT_TENSOR][0], tensor).Fetch(graph[OUTPUT_TENSOR][0]);
var output = runner.Run();
//put results into one dimensional array
float[] probs = ((float[][])output[0].GetValue(jagged: true))[0];
//get max value of probabilities and find its replacedociated label index
float maxValue = probs.Max();
int maxIndex = probs.ToList().IndexOf(maxValue);
//print label with highest probability
string label = labels[maxIndex];
currLabel = label;
}
19
Source : VisualisationEditor.cs
with MIT License
from MaximeCordeil
with MIT License
from MaximeCordeil
public override void OnInspectorGUI()
{
AbstractVisualisation.PropertyType? dirtyFlags = null;
Visualisation targetVisualisation = (Visualisation)serializedObject.targetObject;
serializedObject.Update();
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.PropertyField(uidProperty);
EditorGUI.EndDisabledGroup();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(dataSourceProperty);
if (EditorGUI.EndChangeCheck())
{
loadData();
targetVisualisation.xScatterplotMatrixDimensions = dimensions.Select(x => new DimensionFilter { Attribute = x }).ToArray();
targetVisualisation.yScatterplotMatrixDimensions = dimensions.Select(x => new DimensionFilter { Attribute = x }).ToArray();
targetVisualisation.zScatterplotMatrixDimensions = dimensions.Select(x => new DimensionFilter { Attribute = x }).ToArray();
targetVisualisation.parallelCoordinatesDimensions = dimensions.Select(x => new DimensionFilter { Attribute = x }).ToArray();
}
if (dataSourceProperty.objectReferenceValue != null)
{
//Check if changing the visualisation type
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(visualisationTypeProperty);
if (EditorGUI.EndChangeCheck())
{
dirtyFlags = AbstractVisualisation.PropertyType.VisualisationType;
}
//int visType = visualisationTypeProperty.intValue;
//EnumPopup("Visualisation Type", Enum.GetNames(typeof(AbstractViualisation.VisualisationTypes)), ref visType);
//visualisationTypeProperty.intValue = visType;
EditorGUI.indentLevel++;
// switch ((AbstractViualisation.VisualisationTypes)visualisationTypeProperty.intValue)
switch (targetVisualisation.visualisationType)
{
case AbstractVisualisation.VisualisationTypes.SCATTERPLOT:
ShowSimpleVisualisationMenu(ref dirtyFlags);
break;
case AbstractVisualisation.VisualisationTypes.SCATTERPLOT_MATRIX:
ShowScatterplotMatrixMenu(ref dirtyFlags);
break;
case AbstractVisualisation.VisualisationTypes.PARALLEL_COORDINATES:
ShowParallelCoordinatesMenu(ref dirtyFlags);
break;
case AbstractVisualisation.VisualisationTypes.GRAPH_LAYOUT:
break;
default:
break;
}
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);
EditorGUILayout.LabelField("Aesthetics", EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(geometryProperty);
if (EditorGUI.EndChangeCheck())
{
dirtyFlags = AbstractVisualisation.PropertyType.GeometryType;
}
if (EnumPopup("Colour dimension", dimensions.ToArray(), colourDimensionProperty))
{
dirtyFlags = AbstractVisualisation.PropertyType.Colour;
colorPaletteDimensionProperty.stringValue = "Undefined";
colourPaletteProperty.ClearArray();
colourPaletteProperty.arraySize = 0;
}
if (EnumPopup("Bind Colour palette", dimensions.ToArray(), colorPaletteDimensionProperty))
{
if (colorPaletteDimensionProperty.stringValue != "Undefined")
{
int nbPaletteCategories = dataSource.getNumberOfCategories(colorPaletteDimensionProperty.stringValue);
//float[] uniqueValues = dataSource[colorPaletteDimensionProperty.stringValue].MetaData.categories;
colourPaletteProperty.ClearArray();
colourPaletteProperty.arraySize = nbPaletteCategories;
colourDimensionProperty.stringValue = "Undefined";
}
}
if (colorPaletteDimensionProperty.stringValue != "Undefined" && colorPaletteDimensionProperty.stringValue != "")
{
EditorGUI.BeginChangeCheck();
float[] paletteValues = dataSource[colorPaletteDimensionProperty.stringValue].MetaData.categories;
float[] ordererdPalette = paletteValues.OrderBy(x => x).ToArray();
List<int> sortedId = new List<int>();
//not optimal...
// adding an inderiction pointer indices to reorder values on the GUI -- not sorted in database
for (int idOri = 0; idOri < ordererdPalette.Length; idOri++)
{
//what's the id of the non sorted?
float sortEl = ordererdPalette[idOri];
int _sortedId = paletteValues.ToList().IndexOf(sortEl);
sortedId.Add(_sortedId);
}
int nbPaletteCategories = paletteValues.Length;
EditorGUI.indentLevel += 1;
for (int i = 0; i < nbPaletteCategories; i++)
{
EditorGUILayout.PropertyField(
colourPaletteProperty.GetArrayElementAtIndex(sortedId[i]),
new GUIContent(dataSource.getOriginalValue(paletteValues[sortedId[i]], colorPaletteDimensionProperty.stringValue).ToString())
);
}
EditorGUI.indentLevel -= 1;
if (EditorGUI.EndChangeCheck())
{
dirtyFlags = AbstractVisualisation.PropertyType.Colour;
}
}
if (EnumPopup("Blending Mode Source", Enum.GetNames(typeof(UnityEngine.Rendering.BlendMode)), blendingModeSourceProperty))
{
dirtyFlags = AbstractVisualisation.PropertyType.BlendSourceMode;
}
if (EnumPopup("Blending Mode Destination", Enum.GetNames(typeof(UnityEngine.Rendering.BlendMode)), blendingModeDestinationProperty))
{
dirtyFlags = AbstractVisualisation.PropertyType.BlendDestinationMode;
}
if (colourDimensionProperty.stringValue != "" && colourDimensionProperty.stringValue != "Undefined")
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(colourGradientProperty);
if (EditorGUI.EndChangeCheck())
{
dirtyFlags = AbstractVisualisation.PropertyType.Colour;
}
}
else
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(colourProperty);
if (EditorGUI.EndChangeCheck())
{
dirtyFlags = AbstractVisualisation.PropertyType.Colour;
}
}
if (EnumPopup("Size dimension", dimensions.ToArray(), sizeDimensionProperty))
{
dirtyFlags = AbstractVisualisation.PropertyType.Size;
}
// Size
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(sizeProperty);
EditorGUILayout.PropertyField(minSizeProperty);
EditorGUILayout.PropertyField(maxSizeProperty);
if (EditorGUI.EndChangeCheck())
{
dirtyFlags = AbstractVisualisation.PropertyType.SizeValues;
}
EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);
EditorGUILayout.LabelField("Connectivity", EditorStyles.boldLabel);
if (EnumPopup("Linking dimension", dimensions.ToArray(), linkingDimensionProperty))
{
dirtyFlags = AbstractVisualisation.PropertyType.LinkingDimension;
}
if (EnumPopup("Origin dimension", dimensions.ToArray(), originDimensionProperty))
{
dirtyFlags = AbstractVisualisation.PropertyType.OriginDimension;
}
if (EnumPopup("Destination dimension", dimensions.ToArray(), destinationDimensionProperty))
{
dirtyFlags = AbstractVisualisation.PropertyType.DestinationDimension;
}
if (EnumPopup("Graph dimension", dimensions.ToArray(), graphDimensionProperty))
{
dirtyFlags = AbstractVisualisation.PropertyType.GraphDimension;
}
EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(attributeFiltersProperty, true);
if (EditorGUI.EndChangeCheck())
{
dirtyFlags = AbstractVisualisation.PropertyType.AttributeFiltering;
}
// Visualisation dimensions
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(widthProperty);
EditorGUILayout.PropertyField(heightProperty);
EditorGUILayout.PropertyField(depthProperty);
if (EditorGUI.EndChangeCheck())
{
dirtyFlags = AbstractVisualisation.PropertyType.Scaling;
}
// Update the options for this visualisation
serializedObject.ApplyModifiedProperties();
if (dirtyFlags == AbstractVisualisation.PropertyType.VisualisationType)
targetVisualisation.CreateVisualisation((AbstractVisualisation.VisualisationTypes)visualisationTypeProperty.intValue);
else
if (dirtyFlags != null)
{
targetVisualisation.updateViewProperties(dirtyFlags.Value);
}
}
19
Source : Key.cs
with MIT License
from MaximeCordeil
with MIT License
from MaximeCordeil
public void UpdateProperties(AbstractVisualisation.PropertyType propertyType, Visualisation v)
{
legend = "";
// Size by
if (v.sizeDimension != "Undefined")
legend += "<b>Size By:</b> " + v.sizeDimension + "\n";
// Linking dimension
if (v.linkingDimension != "Undefined")
legend += "<b>Linking Attribute:<b> " + v.linkingDimension + "\n";
// Visualisation can only have a color dimension or a color palette dimension, not both
// Color by
if (v.colourDimension != "Undefined")
{
gradientColorLineRenderer.gameObject.SetActive(true);
legend += "<b>Colour By:</b> " + v.colourDimension + "\n";
SetGradientColor(v.dimensionColour);
}
// Color palette
else if (v.colorPaletteDimension != "Undefined")
{
gradientColorLineRenderer.gameObject.SetActive(false);
legend += "<b>Colour Palette:</b> " + v.colorPaletteDimension + "\n";
List<float> categories = v.dataSource[v.colorPaletteDimension].MetaData.categories.ToList();
string[] values = new string[categories.Count];
for (int i = 0; i < categories.Count; i++)
{
values[i] = v.dataSource.getOriginalValue(categories[i], v.colorPaletteDimension).ToString();
}
// Sort categories
List<float> sortedCategories = categories.OrderBy(x => x).ToList();
for (int i = 0; i < v.coloursPalette.Length; i++)
{
int idx = categories.IndexOf(sortedCategories[i]);
legend += "<color=#" + ColorUtility.ToHtmlStringRGB(v.coloursPalette[idx]) + "> ||||| </color>" + values[idx] + "\n";
}
}
// Hide the gradient if no color by
if (v.colourDimension == "Undefined")
{
gradientColorLineRenderer.gameObject.SetActive(false);
}
Legend.text = legend;
}
19
Source : LinkedVisualisations.cs
with MIT License
from MaximeCordeil
with MIT License
from MaximeCordeil
void CreateMesh()
{
mymesh.Clear();
if (v1.viewType == Visualization.ViewType.Histogram && v2.viewType != Visualization.ViewType.Histogram)
{
//1 get list of axes in v2 and test parallelism
List<Axis> listOfAxes = v2.axes;
List<float> distances = new List<float>();
// the first value is the distance between the histogram and the centre of the visualsiation
distances.Add(Vector3.Distance(v1.axes[0].transform.position, v2.transform.position));
//the rest are the distances between the histogram and each axes
foreach (var item in listOfAxes)
{
distances.Add(Vector3.Distance(item.transform.position, v1.axes[0].transform.position));
}
// the closest item
int indexClosestVisu = distances.IndexOf(distances.ToArray().Min());
// get the corresponding histogram
if (indexClosestVisu > 0)
{
c2 = v2.get1DAxisCoordinates(indexClosestVisu - 1);
}
else c2 = v2.GetPoints();
c1 = v1.GetPoints();
}
else if (v2.viewType == Visualization.ViewType.Histogram && v1.viewType != Visualization.ViewType.Histogram)
{
//1 get list of axes in v2 and test parallelism
List<Axis> listOfAxes = v1.axes;
List<float> distances = new List<float>();
// the first value is the distance between the histogram and the centre of the visualsiation
distances.Add(Vector3.Distance(v1.transform.position, v2.axes[0].transform.position));
//the rest are the distances between the histogram and each axes
foreach (var item in listOfAxes)
{
distances.Add(Vector3.Distance(item.transform.position, v2.axes[0].transform.position));
}
// the closest item
int indexClosestVisu = distances.IndexOf(distances.ToArray().Min());
// get the corresponding histogram
if (indexClosestVisu > 0)
{
c1 = v1.get1DAxisCoordinates(indexClosestVisu - 1);
}
else c1 = v1.GetPoints();
c2 = v2.GetPoints();
}
else
{
c1 = v1.GetPoints();
c2 = v2.GetPoints();
}
pointBuffer.Clear();
indicesBuffer.Clear();
colors.Clear();
normalsBuffer.Clear();
//1 create mesh buffer and indice buffer
if (c1 != null && c2 != null)
{
for (int i = 0; i < c1.Length; i++)
{
if (c1[i] != null && c2[i] != null)
{
pointBuffer.Add(c1[i].Value);
pointBuffer.Add(c2[i].Value);
Color c = VisualisationAttributes.Instance.colors[i];
c.a = VisualisationAttributes.Instance.LinkTransparency;
colors.Add(c);
colors.Add(c);
normalsBuffer.Add(new Vector3(0, 0, 0));
normalsBuffer.Add(new Vector3(0, 0, 1));
}
}
for (int i = 0; i < pointBuffer.Count; i += 2)
{
indicesBuffer.Add(i);
indicesBuffer.Add(i + 1);
}
mymesh.vertices = pointBuffer.ToArray();
mymesh.normals = normalsBuffer.ToArray();
mymesh.SetIndices(indicesBuffer.ToArray(), MeshTopology.Lines, 0);
mymesh.colors = colors.ToArray();
}
}
19
Source : YoloScorer.cs
with MIT License
from mentalstack
with MIT License
from mentalstack
private List<YoloPrediction> ParseSigmoid(DenseTensor<float>[] output, Image image)
{
var result = new ConcurrentBag<YoloPrediction>();
var (w, h) = (image.Width, image.Height); // image w and h
var (xGain, yGain) = (_model.Width / (float)w, _model.Height / (float)h); // x, y gains
var gain = Math.Min(xGain, yGain); // gain = resized / original
var (xPad, yPad) = ((_model.Width - w * gain) / 2, (_model.Height - h * gain) / 2); // left, right pads
Parallel.For(0, output.Length, (i) => // iterate model outputs
{
int shapes = _model.Shapes[i]; // shapes per output
Parallel.For(0, _model.Anchors[0].Length, (a) => // iterate anchors
{
Parallel.For(0, shapes, (y) => // iterate shapes (rows)
{
Parallel.For(0, shapes, (x) => // iterate shapes (columns)
{
int offset = (shapes * shapes * a + shapes * y + x) * _model.Dimensions;
float[] buffer = output[i].Skip(offset).Take(_model.Dimensions).Select(Sigmoid).ToArray();
if (buffer[4] <= _model.Confidence) return; // skip low obj_conf results
List<float> scores = buffer.Skip(5).Select(b => b * buffer[4]).ToList(); // mul_conf = obj_conf * cls_conf
float mulConfidence = scores.Max(); // max confidence score
if (mulConfidence <= _model.MulConfidence) return; // skip low mul_conf results
float rawX = (buffer[0] * 2 - 0.5f + x) * _model.Strides[i]; // predicted bbox x (center)
float rawY = (buffer[1] * 2 - 0.5f + y) * _model.Strides[i]; // predicted bbox y (center)
float rawW = (float)Math.Pow(buffer[2] * 2, 2) * _model.Anchors[i][a][0]; // predicted bbox w
float rawH = (float)Math.Pow(buffer[3] * 2, 2) * _model.Anchors[i][a][1]; // predicted bbox h
float[] xyxy = Xywh2xyxy(new float[] { rawX, rawY, rawW, rawH });
float xMin = Clamp((xyxy[0] - xPad) / gain, 0, w - 0); // unpad, clip tlx
float yMin = Clamp((xyxy[1] - yPad) / gain, 0, h - 0); // unpad, clip tly
float xMax = Clamp((xyxy[2] - xPad) / gain, 0, w - 1); // unpad, clip brx
float yMax = Clamp((xyxy[3] - yPad) / gain, 0, h - 1); // unpad, clip bry
YoloLabel label = _model.Labels[scores.IndexOf(mulConfidence)];
var prediction = new YoloPrediction(label, mulConfidence)
{
Rectangle = new RectangleF(xMin, yMin, xMax - xMin, yMax - yMin)
};
result.Add(prediction);
});
});
});
});
return result.ToList();
}
19
Source : MainPage.xaml.cs
with MIT License
from microsoft
with MIT License
from microsoft
private async Task<string> DetectEmotionWithWinML()
{
var videoFrame = lastFrame;
if (faceDetector == null)
{
faceDetector = await FaceDetector.CreateAsync();
}
var detectedFaces = await faceDetector.DetectFacesAsync(videoFrame.SoftwareBitmap);
if (detectedFaces != null && detectedFaces.Any())
{
var face = detectedFaces.OrderByDescending(s => s.FaceBox.Height * s.FaceBox.Width).First();
using (var randomAccessStream = new InMemoryRandomAccessStream())
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, randomAccessStream);
var softwareBitmap = SoftwareBitmap.Convert(videoFrame.SoftwareBitmap, BitmapPixelFormat.Rgba16);
Debug.WriteLine(softwareBitmap.BitmapPixelFormat);
encoder.SetSoftwareBitmap(softwareBitmap);
encoder.BitmapTransform.Bounds = new BitmapBounds
{
X = face.FaceBox.X,
Y = face.FaceBox.Y,
Width = face.FaceBox.Width,
Height = face.FaceBox.Height
};
await encoder.FlushAsync();
var decoder = await BitmapDecoder.CreateAsync(randomAccessStream);
var croppedImage = await decoder.GetSoftwareBitmapAsync(softwareBitmap.BitmapPixelFormat, softwareBitmap.BitmapAlphaMode);
videoFrame = VideoFrame.CreateWithSoftwareBitmap(croppedImage);
}
}
var input = ImageFeatureValue.CreateFromVideoFrame(videoFrame);
var emotion = await model.EvaluateAsync(new FER_Emotion_RecognitionInput() { Input3 = input });
var list = new List<float>(emotion.Plus692_Output_0.GetAsVectorView());
var index = list.IndexOf(list.Max());
var label = labels[index];
return label;
}
19
Source : Preview.cs
with GNU General Public License v3.0
from mrojkov
with GNU General Public License v3.0
from mrojkov
private void CalcZoomAndMaxZoom()
{
int idenreplacediyZoom = zoomValues.ToList().IndexOf(1.0f);
zoom.Clear();
foreach (var n in RootWidget.Content.Nodes) {
var w = n.Nodes[0] as Widget;
var z = zoomValues.Length - 1;
while (z > 0 && w.MinSize.X * zoomValues[z] > RootWidget.Size.X) {
z--;
}
zoom.Add(new Tuple<int, int>(idenreplacediyZoom > z ? z : idenreplacediyZoom, z));
if (idenreplacediyZoom > z) {
w.MinMaxSize = (Vector2)w.Texture.ImageSize * z;
}
}
}
19
Source : WorldCharacteristicData.cs
with MIT License
from neitsa
with MIT License
from neitsa
protected int FindQuantaIndex(BiomeDef biome, int tileId)
{
var tileAverageTemp = CharacteristicByBiomes[biome][tileId];
var temperatureQuanta = CharacteristicQuantaByBiomes[biome];
var quantaLessThanOrEqu = temperatureQuanta.Where(t => t <= tileAverageTemp).ToList();
if (!quantaLessThanOrEqu.Any())
return 0;
var quantTemp = quantaLessThanOrEqu.Max();
var quantaIndex = temperatureQuanta.IndexOf(quantTemp);
return quantaIndex;
}
19
Source : HandwritingAgent.cs
with MIT License
from remingtonspaz
with MIT License
from remingtonspaz
public override void AgentAction(float[] vectorAction, string textAction)
{
int indexAtMax = vectorAction.ToList().IndexOf(vectorAction.Max()); //get index of max value
//vectorAction contains the confidence values of all possible characters - 62 in total.
string arrStr = "";
//debugs
for (int i = 0; i < vectorAction.Length; i++)
{
arrStr += $"{allChars[i]} {vectorAction[i]:.0000}\n";
}
Debug.Log(gameObject.name+" confidence values:\n"+arrStr);
Debug.Log($"{gameObject.name} prediction result: {allChars[indexAtMax]} {vectorAction[indexAtMax]}");
_lastPredict = allChars[indexAtMax]; //get character with highest confidence
_lastConfidence = vectorAction[indexAtMax];
parsedText += _lastPredict;
if (textMesh) textMesh.text = parsedText;
}
19
Source : YoloScorer.cs
with GNU General Public License v3.0
from Webreaper
with GNU General Public License v3.0
from Webreaper
private List<YoloPrediction> ParseSigmoid(DenseTensor<float>[] output, Image image)
{
var result = new List<YoloPrediction>();
var (xGain, yGain) = (_model.Width / (float)image.Width, _model.Height / (float)image.Height);
for (int i = 0; i < output.Length; i++) // iterate outputs
{
int shapes = _model.Shapes[i]; // shapes per output
for (int a = 0; a < _model.Anchors.Length; a++) // iterate anchors
{
for (int y = 0; y < shapes; y++) // iterate rows
{
for (int x = 0; x < shapes; x++) // iterate columns
{
int offset = (shapes * shapes * a + shapes * y + x) * _model.Dimensions;
float[] buffer = output[i].Skip(offset).Take(_model.Dimensions).Select(Sigmoid).ToArray();
var objConfidence = buffer[4]; // extract object confidence
if (objConfidence < _model.Confidence) // check predicted object confidence
continue;
List<float> scores = buffer.Skip(5).Select(x => x * objConfidence).ToList();
float mulConfidence = scores.Max(); // find the best label
if (mulConfidence <= _model.MulConfidence) // check clreplaced obj_conf * cls_conf confidence
continue;
var rawX = (buffer[0] * 2 - 0.5f + x) * _model.Strides[i]; // predicted bbox x (center)
var rawY = (buffer[1] * 2 - 0.5f + y) * _model.Strides[i]; // predicted bbox y (center)
var rawW = MathF.Pow(buffer[2] * 2, 2) * _model.Anchors[i][a][0]; // predicted bbox width
var rawH = MathF.Pow(buffer[3] * 2, 2) * _model.Anchors[i][a][1]; // predicted bbox height
float[] xyxy = Xywh2xyxy(new float[] { rawX, rawY, rawW, rawH });
var xMin = xyxy[0] / xGain; // final bbox tlx scaled with ratio (to original size)
var yMin = xyxy[1] / yGain; // final bbox tly scaled with ratio (to original size)
var xMax = xyxy[2] / xGain; // final bbox brx scaled with ratio (to original size)
var yMax = xyxy[3] / yGain; // final bbox bry scaled with ratio (to original size)
YoloLabel label = _model.Labels[scores.IndexOf(mulConfidence)];
var prediction = new YoloPrediction(label, mulConfidence)
{
Rectangle = new RectangleF(xMin, yMin, xMax - xMin, yMax - yMin)
};
result.Add(prediction);
}
}
}
}
return result;
}
19
Source : AdeGridManager.cs
with MIT License
from yojohanshinwataikei
with MIT License
from yojohanshinwataikei
public float AttachBeatline(float z)
{
if (!EnableBeatline) return z;
if (beatlineInUse == 0) return z;
List<float> deltas = new List<float>();
for (int i = 0; i < beatlineInUse; ++i)
{
float lz = beatlineInstances[i].GetPosition(0).y;
deltas.Add(Mathf.Abs(lz - z));
}
int index = deltas.IndexOf(deltas.Min());
if (index < 0)
{
return z;
}
float tz = beatlineInstances[index].GetPosition(0).y;
if (Mathf.Abs(tz - z) < 5f) return tz;
return z;
}
19
Source : AdeGridManager.cs
with MIT License
from yojohanshinwataikei
with MIT License
from yojohanshinwataikei
public float AttachVerticalX(float x)
{
if (verticalInUse == 0) return x;
if (verticalXTimings.Count == 0) return x;
List<float> deltas = new List<float>();
for (int i = 0; i < verticalXTimings.Count; ++i)
{
deltas.Add(Mathf.Abs(verticalXTimings[i] - x));
}
int index = deltas.IndexOf(deltas.Min());
if (deltas[index] < 0.3f) return verticalXTimings[index];
else return x;
}
19
Source : AdeGridManager.cs
with MIT License
from yojohanshinwataikei
with MIT License
from yojohanshinwataikei
public float AttachVerticalY(float y)
{
if (verticalInUse == 0) return y;
if (verticalYTimings.Count == 0) return y;
List<float> deltas = new List<float>();
for (int i = 0; i < verticalYTimings.Count; ++i)
{
deltas.Add(Mathf.Abs(verticalYTimings[i] - y));
}
int index = deltas.IndexOf(deltas.Min());
if (deltas[index] < 0.3f) return verticalYTimings[index];
else return y;
}
19
Source : AdeGridManager.cs
with MIT License
from yojohanshinwataikei
with MIT License
from yojohanshinwataikei
public float AttachScroll(float t, float scroll)
{
if (beatlineTimings.Count == 0) return t + 50 * scroll;
List<float> deltas = new List<float>();
for (int i = 0; i < beatlineTimings.Count; ++i)
{
deltas.Add(Mathf.Abs(beatlineTimings[i].Timing - t));
}
int index = deltas.IndexOf(deltas.Min());
index += (scroll > 0 ? 1 : -1);
if (index >= deltas.Count) index = 0;
else if (index < 0) index = deltas.Count - 1;
return beatlineTimings[index].Timing;
}
19
Source : AdeGridManager.cs
with MIT License
from yojohanshinwataikei
with MIT License
from yojohanshinwataikei
public float AttachTiming(float t)
{
if (beatlineTimings.Count == 0) return t;
List<float> deltas = new List<float>();
for (int i = 0; i < beatlineTimings.Count; ++i)
{
deltas.Add(Mathf.Abs(beatlineTimings[i].Timing - t));
}
int index = deltas.IndexOf(deltas.Min());
return beatlineTimings[index].Timing;
}