Drawing lines from pivot points that meet a specific conditions - arrays

I have successfully created a script that draws a line from one pivot point to another based on some conditions.
The conditions are:
The next (or following next) pivot points must have a high that is lower than the original pivot point high
The next (or following next) pivot points must have its wick "touching" the original wick
It is not allowed to draw a line if there is any higher high in the range between the original pivothigh wick and the current pivothigh wick. If several conditions are meet, a "fan of lines" from the original pivot high can be created.
I asked a question about this before here Creating a fan of lines in pinescript
I managed to do this using arrays. Result can been seen here. Purple lines are "hand drawn" and the white dashed lines comes from the script.
So far so good. BUT I have 3 problems/issues:
When a new candle is created the script fails due to "range out of bounds". I know it comes from the var declarations of the arrays on lines 19-22. If on the 1h or above timeframe it's not a big issue but on 1m it's very annoying. But deleting the var it doesn't compile correctly.
It's slow. Takes a couple of seconds to compute even though I'm using a while statement that prevents the "lookback" if a "top" has been detected. Then it's no longer necessary to look back anymore.
Related to (2). I'm suspecting there is a much smarter way to do this in pinescript but I haven't figured it out yet without the use of arrays.
Here's the code.
Is it possible to do this without arrays to solve all my 3 issues above?
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sincereStork12718
//#version=5
indicator("Pivot lines", overlay=true, max_boxes_count=500, max_lines_count=500)
//---------------------------------------
//Variable declaration
//---------------------------------------
nbrBars = bar_index
plot (nbrBars, title = "nbrBars", display = display.data_window)
plot(last_bar_index, title = "last_bar_index", display = display.data_window)
//---------------------------------------
// Pivot to downside with ARRAYS working 99.9%
//---------------------------------------
//Declare arrays
var index_array_bear = array.new<int>(last_bar_index)
var high_array = array.new<float>(last_bar_index)
var upwick_array = array.new<float>(last_bar_index)
var shadow_high = array.new<float>(last_bar_index+1)
isAttFUBear = ta.pivothigh(1,1) // For this example ta.pivothigh(1,1) will produce the same result
isFUBear = ta.pivothigh(1,1) //For this example ta.pivothigh(1,1) will produce the same result
//Get bar_index, the high and the start of the upper wick for all AttFU/FU to the downside in the series from first to last bar
var i_dn = 0
if (isAttFUBear or isFUBear) == 1
array.set(index_array_bear, i_dn, bar_index[1])
array.set(high_array, i_dn, high[1])
array.set(upwick_array, i_dn, math.max(open[1], close[1]))
i_dn += 1
var j_dn = 0
array.set(shadow_high, j_dn, high)
j_dn += 1
//Draw line from index n to all index n++ that satisfies the condition below
//1. n++ index must be lower than the n:th index, i.e. high[n++] < high[n]
//2. n++ index must have it's high above upwick of the n:th, i.e. high[n++] > upwick[n]
//3. There must be a filter that removes any high higher than high[n] and high[n++] to not draw any unneccesary lines, i.e. if a "top" is found is not longer neccecary to look backwards
cnt1 = 1
top_found = false
while i_dn >= 2 and i_dn-1-cnt1 >= 0 and top_found == false
if array.get(high_array, i_dn-1-cnt1) > array.get(high_array, i_dn-1) //Checking if previous FU is higher than the current, if NOT, check the next previous etc.
if array.get(high_array, i_dn-1) >= array.get(upwick_array, i_dn-1-cnt1) //Check if current high is retesting the wick of the previous
//testing filter high in between
high_in_range = array.new<float>(nbrBars) //Create temporary array that stores all high values between the first and last endpoints of the line
for cnt2 = array.get(index_array_bear, i_dn-1-cnt1) to array.get(index_array_bear, i_dn-1)
array.set(high_in_range, cnt2, array.get(shadow_high, cnt2))
max_high_in_range = array.max(high_in_range, 2) //Return the second highest high within the range (excluding the i-1-cnt1 which is the higest)
if array.get(high_array, i_dn-1) > max_high_in_range
line.new(array.get(index_array_bear, i_dn-1-cnt1), array.get(high_array, i_dn-1-cnt1), array.get(index_array_bear, i_dn-1), array.get(high_array, i_dn-1), color = color.white, style = line.style_dashed, width = 1)
if i_dn-1-cnt1-1 > 0 //Checking if current lookback FU is higher than previous and next. If true then stop the search
if array.get(high_array, i_dn-1-cnt1) > array.get(high_array, i_dn-1-cnt1+1) and array.get(high_array, i_dn-1-cnt1) > array.get(high_array, i_dn-1-cnt1-1)
top_found := true
cnt1 := cnt1 +1

Related

How to calculate rotation speed based on deltax?

To give context, I'm trying to clone Wolfenstein 3D using C. I'm at a position where my game is fully functional and can move and rotate point of view using keys, however i'm trying to add the functionality of changing point of view using mouse too, and i managed to do so but the result is not as expected.
in my key based rotation I have a constant variable with which the player rotate at a constant speed all the time, however with mouse it's a bit different the user move the cursor fast or slow and depending in the latter rotation speed should be incremented or decremented accordingly, to just imitate the latter , i coded a stupid if else tree to configure rotation speed of the player, something as basic as that:
diff = abs(x - prev_x);
if (diff < 100)
rot_spd = degtorad(2);
else if (diff > 100 && diff < 200)
rot_spd = degtorad(3);
else if (diff > 200 && diff < 300)
rot_spd = degtorad(4);
...
The question is:
given a deltaX = abs(x - pervious_x) where x and pervious_x is position of cursor at a given time is there a mathematical formula or a better a way than if else to configure with which speed in degrees the player will rotate the Point of view.
Based on the numbers you have used in your if / else expressions you could use:
diff = abs(x - prev_x);
rot_spd = degtorad(diff / 100 + 2);
This assumes diff is an integer type, so that when divided the fractional part of the result is discarded and the result is truncated towards zero.
It will also cover the cases where diff is an exact multiple of 100, which your code does not cater for just now. You would need to add an equality check in your if else expressions.

Partition n players into two teams of size k and equal (or minimally different) strength

I came across this question recently; I thought about it a lot but could not find a solution:
Given a list of n players with strengths [s1 , s2, s3 ... sn], create two teams (A and B) of size k (k ≤ n/2), so that:
the total strength is maximized
the difference in strength is minimized
Strength(A) = sum of strength of all players in team A,
Strength(B) = sum of strength of all players in team B,
Total strength = strength(A) + strength (B),
Difference in strength = abs(strength(A) - strength(B)).
In case of same total strength, select the combination with the minimum difference in strength.
Example:
n = 5; k = 2
players: a b c d e
strength: 4 4 2 2 5
Option Team A Team B Strength Difference
1 [a,b] [c,e] 15 1
2 [a,b] [d,e] 15 1
3 [a,c] [b,e] 15 3
4 [a,d] [b,e] 15 3
5 [a,c] [b,d] 12 0
6 [a,d] [c,b] 12 0
7 [a,d] [c,e] 13 1
Option 1 and option 2 are winning combinations as their total strength is 15 (maximum), while their difference in strength is closer to the minimum than options 3 and 4.
My thoughts:
If 2k = n , strength is taken care of already (because all elements will be involved) and we just need to find two halves such that difference of sum of these two is minimum. But how to find that efficiently?
If 2k < n , we can probably sort the strength array and removed n-2k smallest elements and then we are back to 2k = n situation.
As mentioned in the comments, this is a variant of the Partitioning Problem, which itself is a special case of the Subset Sum Problem. These indeed have dynamic programming and approximation solutions, which you may be able to adapt to this problem. But the specific requirement of two equal-sized teams means that non-dp and non-greedy solutions are possible too.
Firstly, optimizing for total strength before taking the difference in strength between the teams into account, means that when the number of players n is odd, the weakest player can be discarded, and the size of the teams k is always half of n. If k is given as part of the input, then take the 2×k strongest players and discard the others.
(You could wonder whether the question was in fact to optimize for strength difference first, and then for total strength. If you find two subsets with difference x, then finding another two subsets with a similar difference y would mean you can combine them into two larger subsets with a smaller difference of |x-y|. This is an obvious basis for a dynamic programming approach.)
Alternative to dynamic programming solution
Let's look at the example of splitting n=23 (i.e. n=22) players into two teams of 11 players. If we used brute force to look at every option, we'd keep one of the players in team A (to avoid duplicate solutions) and try every combination of 10 additional players from the 21 others to complete team A. That means there are:
(n-1 choose k-1) = (21 choose 10) = 352,716 unique options
While this is a feasible number of options to check, larger numbers of players would quickly result in huge numbers of options; e.g. splitting 44 players into two teams of 22 would lead to more than 1012 options.
We can drastically reduce the number of options that need to be checked, by starting with an initial split into two teams, and then checking which 1 player, 2 players, ... , 10 players we'd need to swap to reduce the strength difference the most. This can be done without having to consider swapping each possible subset of team A with each possible equal-sized subset of team B.
We could do the initial split into teams randomly, but if we sort the players by strength, and alternatingly add a player to team A or team B, this should limit the initial difference in strength D, which in turn should make it more likely that a solution with a limited number of swaps is found quickly (if there are several perfect solutions).
Then we consider swapping 1 player; we make a list of all players in team A (except the first one, which we'll always keep in team A to avoid duplicate solutions) and sort it from weakest to strongest. We also make a list of all players in team B, and sort it from weakest to strongest. Then we iterate over both lists at the same time, at each step moving to the next value in the list that brings the difference in strength between the current player from team A and team B closer to the initial value of D.
Note that we don't compare every player in the first list with every player in the second list in a nested loop. We only iterate over the lists once (this is similar to finding the two integers with the smallest difference in two arrays; see e.g. here).
If we come across a pair of players that, when swapped, decreases D, we store this pair and set the new value of D.
Now we consider swapping 2 players; we make a list of every pair of 2 players from team A (excluding player 1 again) and a list of every pair of players from team B, sort the lists from weakest to strongests (adding the strength of the two players). Then we iterate over both lists again, looking for a pair of pairs that, when swapped, decreases the value of D.
We go on doing the same for sets of 3, 4, ... 10 players. For the example of 23 players, the size of these lists would be:
team A team B
swap 1 10 11
swap 2 45 55
swap 3 120 165
swap 4 210 330
swap 5 252 462
swap 6 210 462
swap 7 120 330
swap 8 45 165
swap 9 10 55
swap 10 1 11
---- ----
1023 2046
So, we'd find the optimal swap that results in two teams with the smallest difference in strength after at most 3,069 steps instead of 352,716 steps for the brute-force algorithm.
(We could further speed up the cases where there are several perfect solutions by checking swap sizes in the order 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 to find a solution without having to generate the larger lists.)
The example of splitting 44 players into two teams of 22 would take at most 6,291,453 steps instead of more than 1012 steps. In general, the maximum number of steps is:
2k + 2k−1 − 3
and the time complexity is:
O(2k)
which doesn't look great, but is much better than the brute-force algorithm with its O(C(n-1,k-1)) complexity. Also, as soon as a solution with difference 0 or 1 is found, there is no need to look at further options, so a solution can be found after considering swaps of only 1 or a handful of players, and the average case complexity is much better than the worst-case complexity (this is discussed further below.)
Code example
Here's a Javascript code snippet as a proof of concept. Selections of players are represented by a bit array (you could also use an integer as a bit pattern). You'll see that the change in team strength after different swaps is calculated, but only one selection of players is actually swapped at the end; so it's not a greedy algorithm that gradually improves the strength difference by performing several swaps.
function compareStrength(a, b) { // for sorting players and selections
return a.strength - b.strength;
}
function teamStrength(players) {
return players.reduce(function(total, player) {return total + player.strength;}, 0);
}
function selectionStrength(players, selection) {
return players.reduce(function(total, player, index) {return total + player.strength * selection[index];}, 0);
}
function nextPermutation(selection) { // reverse-lexicographical next permutation of a bit array
var max = true, pos = selection.length, set = 1;
while (pos-- && (max || !selection[pos])) if (selection[pos]) ++set; else max = false;
if (pos < 0) return false;
selection[pos] = 0;
while (++pos < selection.length) selection[pos] = set-- > 0 ? 1 : 0;
return true;
}
function swapPlayers(wTeam, sTeam, wSelect, sSelect) {
for (var i = 0, j = 0; i < wSelect.length; i++) {
if (wSelect[i]) {
while (!sSelect[j]) ++j;
var temp = wTeam[i];
wTeam[i] = sTeam[j];
sTeam[j++] = temp;
}
}
}
function equalTeams(players) {
// SORT PLAYERS FROM WEAKEST TO STRONGEST
players.sort(compareStrength);
// INITIAL DISTRIBUTION OF PLAYERS INTO WEAKER AND STRONGER TEAM (ALTERNATING)
var wTeam = [], sTeam = [];
for (var i = players.length % 2; i < players.length; i += 2) {
wTeam.push(players[i]);
sTeam.push(players[i + 1]);
}
var teamSize = wTeam.length;
// CALCULATE INITIAL STRENGTH DIFFERENCE
var initDiff = teamStrength(sTeam) - teamStrength(wTeam);
var bestDiff = initDiff;
var wBestSel = [], sBestSel = [];
// CHECK SELECTIONS OF EVERY SIZE
for (var selSize = 1; selSize < teamSize && bestDiff > 1; selSize++) {
var wSelections = [], sSelections = [], selection = [];
// CREATE INITIAL SELECTION BIT-ARRAY FOR WEAKER TEAM (SKIP PLAYER 1)
for (var i = 0; i < teamSize; i++)
selection[i] = (i > 0 && i <= selSize) ? 1 : 0;
// STORE ALL SELECTIONS FROM WEAKER TEAM AND THEIR STRENGTH
do wSelections.push({selection: selection.slice(), strength: selectionStrength(wTeam, selection)});
while (nextPermutation(selection));
// SORT SELECTIONS FROM WEAKEST TO STRONGEST
wSelections.sort(compareStrength);
// CREATE INITIAL SELECTION BIT-ARRAY FOR STRONGER TEAM
for (var i = 0; i < teamSize; i++)
selection[i] = (i < selSize) ? 1 : 0;
// STORE ALL SELECTIONS FROM STRONGER TEAM AND THEIR STRENGTH
do sSelections.push({selection: selection.slice(), strength: selectionStrength(sTeam, selection)});
while (nextPermutation(selection));
// SORT SELECTIONS FROM WEAKEST TO STRONGEST
sSelections.sort(compareStrength);
// ITERATE OVER SELECTIONS FROM BOTH TEAMS
var wPos = 0, sPos = 0;
while (wPos < wSelections.length && sPos < sSelections.length) {
// CALCULATE STRENGTH DIFFERENCE IF THESE SELECTIONS WERE SWAPPED
var wStrength = wSelections[wPos].strength, sStrength = sSelections[sPos].strength;
var diff = Math.abs(initDiff - 2 * (sStrength - wStrength));
// SET NEW BEST STRENGTH DIFFERENCE IF SMALLER THAN CURRENT BEST
if (diff < bestDiff) {
bestDiff = diff;
wBestSel = wSelections[wPos].selection.slice();
sBestSel = sSelections[sPos].selection.slice();
// STOP SEARCHING IF PERFECT SOLUTION FOUND (DIFFERENCE 0 OR 1)
if (bestDiff < 2) break;
}
// ADVANCE TO NEXT SELECTION FROM WEAKER OR STRONGER TEAM
if (2 * (sStrength - wStrength) > initDiff) ++wPos; else ++sPos;
}
}
// PERFORM SWAP OF BEST PAIR OF SELECTIONS FROM EACH TEAM
swapPlayers(wTeam, sTeam, wBestSel, sBestSel);
return {teams: [wTeam, sTeam], strengths: [teamStrength(wTeam), teamStrength(sTeam)]};
}
var players = [{id:"Courtois", strength:65}, {id:"Mignolet", strength:21}, {id:"Casteels", strength:0},
{id:"Alderweireld", strength:83}, {id:"Vermaelen", strength:69}, {id:"Kompany", strength:82},
{id:"Vertonghen", strength:108}, {id:"Meunier", strength:30}, {id:"Boyata", strength:10},
{id:"Dendoncker", strength:6}, {id:"Witsel", strength:96}, {id:"De Bruyne", strength:68},
{id:"Fellaini", strength:87}, {id:"Carrasco", strength:30}, {id:"Tielemans", strength:13},
{id:"Januzaj", strength:9}, {id:"Dembele", strength:80}, {id:"Chadli", strength:51},
{id:"Lukaku", strength:75}, {id:"E. Hazard", strength:92}, {id:"Mertens", strength:75},
{id:"T. Hazard", strength:13}, {id:"Batshuayi", strength:19}];
var result = equalTeams(players);
for (var t in result.teams) {
for (var i in result.teams[t]) {
document.write(result.teams[t][i].id + " (" + result.teams[t][i].strength + ") ");
}
document.write("<br>→ team strength = " + result.strengths[t] + "<br><br>");
}
Probability of finding a perfect solution
When the algorithm finds a perfect solution (with a strength difference of 0 or 1), this cannot be improved further, so the algorithm can stop looking at other options and return the solution. This of course means that, for some input, a solution can be found almost instantly, and the algorithm can be used for a large number of players.
If there is no perfect solution, the algorithm has to run its full course to be sure it has found the best solution. With a large number of players, this could take a long time and use a lot of memory space (I was able to run a C++ version for up to 64 players on my computer).
Although it's straightforward to craft input that has no perfect solution (such as one player with strength 3 and the other players all with strength 1), testing with random data showed that the number of players for which almost all random input has a perfect solution is surprisingly low (similar to the Birthday Paradox).
With n=24 (two teams of 12) or more, ten million instances of random input provided not a single case where the strength difference between the teams was greater than 1, whether using 10, 100, 1000 or 10000 different integer values to express the strength of each player.

Infinite loop by creating arrays to swap node positions

There are 20 red balls sitting in 20 positions on 4 shelves. I'd like to move each ball to a new position on its own shelf by generating a new array that contains the new positions for all 20 balls. I am using a function (below) that allows me to do this. However, I find that this function keeps crashing; when I print out values it is generating, it seems to hang at the last coordinate of available position but then doesn't exit the "while" loop.
func generateNewLocationArray(previous: [String: CGPoint]) -> [String : CGPoint] {
var refreshedLocations = [String : CGPoint]()
for (location, _) in previous {
let node = fgNode.childNode(withName: location) as? LocationNode
var newLocation = generateRandomLocation(check: refreshedLocations)
let previousLocation = previous[(node?.name!)!]
while (newLocation == previousLocation) || (newLocation.y != previousLocation?.y) {
newLocation = generateRandomLocation(check: refreshedLocations)
}
node?.position = newLocation
refreshedLocations[location] = newLocation
}
return refreshedLocations
}
What I'm trying to achieve:
The function takes in an array of CGPoints, this is the "previous"
array, of positions where all the balls were.
It then creates a brand-new array, called "refreshedLocations".
It loads an existing node, which is located at a position contained in the previous array.
It then generates a new position for that node. This position is obtained from a pre-set array of 20 positions. This new location cannot be the same position the node is currently in; nor can it have a different y-coordinate (so the balls stay on the shelf).
Until this criteria is met, it keeps generating a new position.
It then loads this position into the refreshedLocations array, and the next node is also checked against this array to ensure there are no repeated positions.
The problem again: this code works with 10, or 15 balls. But when the number is pushed to 20, it seems more likely to hang. It will identify how to move all the balls around to new positions, but it gets stuck in the "while" loop more often than not. What's going wrong here?
EDIT: This is the function which returns a random location, but first checks whether the array that is being generated already contains the point being added.
func generateRandomLocation(check: [String : CGPoint]) -> CGPoint {
let randomIndex = GKRandomDistribution(lowestValue: 0, highestValue: allPositions.count - 1)
var position = allPositions[randomIndex.nextInt()]
while check.values.contains(position) {
position = allPositions[randomIndex.nextInt()]
}
return position
}
As far as I can see,
while (newLocation == previousLocation) || (newLocation.y != previousLocation?.y)
is always going to be true if you get to the last ball on a row and the only position left is the one it is already in. You can fix it by detecting how many positions on the shelf have been filled and if it is n - 1 out of n and the only position left is the one the ball is in, just swap it with a randomly selected other ball on the same shelf.
However, there must be a better way of doing this. I'd try a modified Fisher Yates shuffle.
Firstly, organise the balls by shelf and position. Then, for each shelf of n balls (numbered 0 to n - 1)
select a random ball from the first n - 2 balls and swap it with ball n - 1
select a random ball from the first n - 3 balls and swap it with ball n - 2
select a random ball from the first n - 4 balls and swap it with ball n - 3
and so on. Stop when the random selection would be from 0 balls. At the end of this process, all the balls will have changed position.
Repeat for each shelf.

MATLAB: signal clipping method skips array indexes?

The problem: I have roughly isolated data points of the baselines either side of a square pulse signal. I now want to clip these arrays of data points from the 'pulse end' to their respective means (because I still have some data points from the rise and fall of the signal).
As you can see my method appears to work when starting at the end of an array and clipping backwards, but seems to skip data points when assessing array indexes starting from the beginning of the array.
The code:
baseline1=[1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,3,4;1:18];
baseline2=[4,3,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1;32:49];
%---------------------------------------------------
figure()
hold on
plot(baseline1(2,:),baseline1(1,:),'k')
plot(baseline2(2,:),baseline2(1,:),'k')
%---------------------------------------------------
%Clip baseline1
arrayMean = mean(baseline1(1,:));
x=size(baseline1,2);
meanCrossed = 0;
arrayClipped = baseline1;
for i=x:-1:1
if baseline1(1,i)>arrayMean && meanCrossed == 0
arrayClipped(:,i)=[];
else
meanCrossed = 1;
end
end
baseline1=arrayClipped;
%---------------------------------------------------
%Clip baseline2
arrayMean = mean(baseline2(1,:));
x=size(baseline2,2);
meanCrossed = 0;
arrayClipped = baseline2;
for i=1:x
if baseline2(1,i)>arrayMean && meanCrossed == 0
arrayClipped(:,i)=[];
else
meanCrossed = 1;
end
end
baseline2=arrayClipped;
%---------------------------------------------------
plot(baseline1(2,:),baseline1(1,:),'g','LineWidth',2)
plot(baseline2(2,:),baseline2(1,:),'g','LineWidth',2)
Can anyone advise?
Say you want to delete indices 4 then 2 from a vector of size 4. 4 goes away, so now it's size 3. 2 goes away, making it size 2:
1 2 3 4
1 2 3
1 3
Now say you want to delete indices 2 then 4. 2 goes away, so now it's size 3. Now we delete index 4.... WAIT A SECOND!
1 2 3 4
1 3 4
Index 4 doesn't exist, because we shortened the array. The element formerly known as the 4th element is now at index 3.
By deleting elements, you're changing the indexing of all elements from that point forward. Solution: save all the indices as you compute, and delete them all afterwards:
for ...
clipped_indices(end+1) = i;
end
arrayClipped(:, clipped_indices) = [];
Or, for a cleaner and faster implementation, don't make arrayClipped at all. Instead, make an logical array of all ones of the correct size, and zero them as you find the elements to clip, then index baseline2 with the resulting logical array at the end.
My working solution inspired by the answer:
%Data points on the rise and fall of the square wave are recursively clipped to the
%baseline of their respective arrays. With each loop the mean is reassessed
%and the end of the array clipped to the new mean.
%Clip baseline1
sizeStable = 0; %set flag
while sizeStable == 0
arrayMean = mean(baseline1(1,:)); %(re)calculate mean
x=size(baseline1,2); %(re)calculate size
meanCrossed = 0; %(re)set
for i=x:-1:1 %from x to 1 in steps of -1
if baseline1(1,i)>arrayMean && meanCrossed == 0 %if the data point is greater than the mean and the mean has not been crossed before
baseline1(:,i)=0; %make the entire column at that index zero
else
meanCrossed = 1;
end
end
baseline1( :, ~any(baseline1,1) ) = []; %delete columns with zeros
if size(baseline1,2) == x
sizeStable = 1;
end
end

How to save part of image in arrays or matrices in Matlab

I am developing a project of detecting vehicles' headlights in night scene. I am working on a demo on MATLAB. My problem is that I need to find region of interest (ROI) to get low computing requirement. My solution is calculating total intensity per row and if the row's intensity is below threshold, it is blacked.
[rows col] = size(img1);
sumValue=[];
sum1 = sum(sum(img1)/(rows*col));
for a=1:1:rows
sumValue = sum(img1(a,:))/col;
if (sumValue <sum1+40)
img1(a,:)=0;
end
end
And here is the result:
Now i want to save the bright parts of image in arrays or matrices so that i can delete the small bright parts and keep only large part. If anyone has any idea, plz give me some suggestions.
I'm sure this could be optimised a bit more.
new_im = zeros(size(im));
% Loop through each column
for c=1:1:size(im,2)
column = im(:,c);
% The first non-zero value in each column will be the top of the window
upper_candidates = find(column>0);
top = upper_candidates(1);
% The first zero value after that will be your lower boundary
lower_candidates = find(column(top:end) == 0);
bottom = lower_candidates(1);
% Insert each column into the new image
new_im = im(top:bottom,c);
end

Resources