Display the segmentation of watershed algorithm
I am a newbie to Opencv, I have recently been using the watershed algorithm, Currently i have tried to segment the images using different color markers,but i wanted to display the segments as well.
Is there any method by which this can be done, as we can do it in Simple Linear Iterative Clustering superpixel segmentation using Simple Linear Iterative Clustering function and mark boundaries function
Using Opencv and python.
Thanks.
1 answer

First follow THIS DOCUMENTATION to obtain the markers in the image. I used the same image present in this documentation.
After that follow this code linebyline and visualize what each variable contains:
Each unique connected component is assigned a unique value in the variable
markers
. I am normalizing those values present inmarkers
to an integer. Each connected component can be obtained at a particular threshold value mentioned in the listuniq_thresh
.label_hue = np.uint8(179*markers/1) uniq_thresh = np.unique(label_hue).tolist() cv2.imshow('label_hue', label_hue) uniq_thresh.sort(reverse=True)
prev
is an image having the same shape as the original image but with pixels of value 0 throughout.prev = np.zeros_like(label_hue)
Now for each of the unique threshold value in the list
uniq_thresh
I am displaying the connected component. But sincethresh
returns an image having componets above a certain threshold I am subtracting the previous threshold image from it in order to obtain a single component.for th in uniq_thresh: print(th) ret, thresh = cv2.threshold(label_hue, th, 255, cv2.THRESH_BINARY) cv2.imshow('ind', thresh) cv2.imshow('ind2', thresh  prev) prev = thresh cv2.waitKey(0) cv2.destroyAllWindows()
See also questions close to this topic

Syntax error is not actually an error
I am doing this problem:
Finding Numbers in a Haystack
In this assignment you will read through and parse a file with text and numbers. You will extract all the numbers in the file and compute the sum of the numbers.
Data Files
We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment. Sample data: http://py4edata.drchuck.net/regex_sum_42.txt (There are 90 values with a sum=445833)
 Actual data: http://py4edata.drchuck.net/regex_sum_97463.txt (There are 82 values and the sum ends with 873)
These links open in a new window. Make sure to save the file into the same folder as you will be writing your Python program.
Note: Each student will have a distinct data file for the assignment  so only use your own data file for analysis.
I wrote this code:
import re fname = input('Enter a file name: ') try: fhandle = open(fname) except: print ('File cannot be opened:', fname) exit() numlist = list() for line in fhandle: line = line.rstrip() num = re.findall('^New .*: ([09]+)', line) if len(num) > 0: for number in num: number =`enter code here` float(number) numlist.append(number) print (sum(numlist))
it should run, but I get an error at line six at the print statement. I have put a link to the error that comes to screen in the picture. Any advice or solution is greatly appreciated

Yield usage in recursive manner
I was playing around with the
yield
and I made up a function that takes 3 numbers and a limit and computes them in a particular way (the computation is not important, but can be seen in the code below).values = [] def compute(limit, a, b, c): if a <= limit: print("Got {}, {}, {}".format(a, b, c)) values.append([a, b, c]) compute(limit, b*c, a*c, a*b) else: print("Process ended") compute(9999, 2, 3, 4) print(values)
This works, and produces the output:
Got 2, 3, 4 Got 12, 8, 6 Got 48, 72, 96 Got 6912, 4608, 3456 Process ended [[2, 3, 4], [12, 8, 6], [48, 72, 96], [6912, 4608, 3456]]
However, I am sure that this can be done with the usage of
yield
 mainly thevalues
list creation part, which, as you see, is filled manually by me in the function.The reason why I bother at all is just why the
yield
is used in the first place  here it doesn't matter, but what if my task required the 100000th value from this list  constructing it as a whole is not required, or even plainly stupid considering I don't want the previous 99999 values...I tried using something like:
def compute_y(a, b, c): while True: yield b*c, a*c, b*a for a, b, c in compute_y(2, 3, 4): if a > 9999: break
The problem with this is that the numbers in the
for
are the same all the time (2, 3 and 4), so it's never gonna reach other values and because of that it's an infinite loop.tl;dr  can I use yield here at all to make the algorithm more efficient for bigger lists?

Getting the sum of groupby as a new column with distinct values in Pandas
This is how my data look like:
id date rt dnm 101122 20170124 0.0 70 101122 20170108 0.0 49 101122 20170413 0.02976 67 101122 20170803 1.02565 39 101122 20161201 0.0 46 101122 20170125 0.0 69 101122 20170102 0.0 76 101122 20170718 0.02631 38 101122 20160602 0.0 120 221344 20161021 0.00182 176 221344 20160921 0.47732 194 221344 20160623 0.0 169 221344 20171010 0.91391 151 221344 20170429 0.0 33 221344 20170205 0.0 31 221344 20171016 0.0 196 221344 20160925 0.0 33 221344 20160717 0.0 21 221344 20160721 0.0 46 615695 20170712 0.0 21 615695 20170705 0.0 18 615695 20160711 0.0 38 615695 20160719 0.03655 29 615695 20170527 0.0 23 615695 20171222 0.0 20 615695 20170425 0.0 34 615695 20170323 0.0 20 615695 20160923 0.0 25 615695 20160618 0.0 25
I'm trying to get the sum of 'dmn' column for each 'id' and give this new column a name like 'sum_values'. After that I need to get the id's that have the 'sum_values' higher than 300. The following code generates the first part:
data = pd.read_csv(file_name, sep='\t', header=0, parse_dates=[1], infer_datetime_format=True); test = (data.assign(sum_values = data.groupby('id')['dnm'].transform(np.sum)) .query('sum_values > 300'))
This will add a new column named 'sum_values' and repeat the sum value for each id several times. I need to get a unique value of 'id' and 'sum_values' column. But I can't figure out how/where to add the nunique().
This is the desired outcome:
id sum_values(>300) 101122 574 221344 1050
Any ideas?

get number of hours of specific timeperiod in another timeperiod
Struggling with that very much so let me pain You a scenario:
waiter at restaurant earns 15$/hour but between 21.00 and 02.30 he gets paid additionaly 3$/hour. now what I have is 'start' and the 'end' of the shift as Date object and I want to calculate how many hours of that extra paidperiod is in the shift if there is any.(keep in mind start and end time of shift can be anythingand bc of that it gets difficult)
I made it work by using alot of ifstatements but that definitly can not be the right way of doing it. I'm adding my code here link but It's a mess just so U know(have two different timeperiod with extra pay in that code fui). Any one have an idea of better way of calculate that?(any classes that can be of any help here?)
static calculateShiftSalary(shift: Shift, employee: Employee): Shift { const extraPaidStart = 22 const extraPaidEnd= 2.5 // meaning 02.30 o'clock of the next day here let start:Date = shift.startDate let end:Date = shift.endDate let extraHours:number = getNumberOfExtraPaidHours(start,end,extraPaidStart,extraPaidEnd) }
so if U'd would have a shift between 20.00 and 23.30 >'extraHours'=1,5 and if shift would be between 23.00 and 02.00 >extraHours=3h
extraPaidStart and extraPaidEnd can be change to a Date ofc if that would be to any help (y)

Double every time brings different values
It's my generating algorithm it's generating random double elements for the array which sum must be 1
public static double [] GenerateWithSumOfElementsIsOne(int elements) { double sum = 1; double [] arr = new double [elements]; for (int i = 0; i < elements  1; i++) { arr[i] = RandomHelper.GetRandomNumber(0, sum); sum = arr[i]; } arr[elements  1] = sum; return arr; }
And the method helper
public static double GetRandomNumber(double minimum, double maximum) { Random random = new Random(); return random.NextDouble() * (maximum  minimum) + minimum; }
My test cases are:
[Test] [TestCase(7)] [TestCase(5)] [TestCase(4)] [TestCase(8)] [TestCase(10)] [TestCase(50)] public void GenerateWithSumOfElementsIsOne(int num) { Assert.AreEqual(1, RandomArray.GenerateWithSumOfElementsIsOne(num).Sum()); }
And the thing is  when I'm testing it returns every time different value like this cases :
Expected: 1 But was: 0.99999999999999967d
Expected: 1 But was: 0.99999999999999989dBut in next test, it passes sometimes all of them, sometimes not.
I know that troubles with rounding and ask for some help, dear experts :)

Automatic tree drawing
I have the following algorithm,
f(C,n) = if (C<0 or i=0) then 0 else if (C=0) then 1 else f(CP[n],n1)+f(C,n1)
the recursive calls of which i'd like to model in a binary tree. Is there a tool that could do this for a specific input? I'd really like to avoid drawing it by hand.

OpenCV imread of png
I am currently working on a python script using Anaconda, in which I need to read a regular screenshot  that I have taken with the standard DesktopApp SnippingTool  which is of format
PNG
. For some reason the commandcv2.imread()
is returningNone
for any taken screenshot, but is working perfectly fine for any otherpng
image. What can I do/ what am I doing wrong?Here is my code:
import cv2 img1 = cv2.imread("C:\\Users\\Desktop\\Screenshot.PNG", 0) //Returns "None" img2 = cv2.imread("C:\\Users\\Desktop\\RandomImage.png", 0) //Works fine
I have seen other people with the same problem, but mostly the solution was just to switch to using
JPG
files which unfortunately is not an option for me. Alsolibpng
is updated to the newest version 1.6.34. 
Wrong HSV conversion from RGB (OpenCV, Python)
I have these lists containing
blue values
in RGB format.low = [ [0, 0, 128], [65, 105, 225], [70, 130, 180], [72, 61, 139], [83, 104, 120] ]
What I want to make is this: convert all the values from, for example, first list from RGB to HSV.
I made this code:
import cv2 import numpy as np for v in low: rgb = np.uint8([[v]]) print("RGB: ", rgb) hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV) print("HSV: ", hsv) print("\n")
The problem is when I go to check if the colors (RGBHSV) are the same. Here I discover that it's not.
Let's take the last value from
low list
.RGB: [[[ 83 104 120]]] HSV: [[[103 79 120]]]
RGB is RGB input value and HSV is output. But this last one it's not the same color as RGB. First is a shade of blue and last is green. Why ?
I used this tool to check values. It also says that the right HSV for this RGB should be
205, 30, 47
Where I get wrong ?
Thanks

Open CV  iOS PNG Overlaying images with transparent background shows white background
I am using following open cv method to convert UIImage to Matrix.
cv::Mat gtpl;// Stores BGRA matrix UIImage *tplImg = [UIImage imageNamed:@"lion"]; cv::Mat tpl; UIImageToMat(tplImg, tpl); //Converts Image to Matrix cv::cvtColor(tpl, gtpl, CV_RGBA2BGRA); // Converts matrix to 4 channels and save into gtpl variable. //While Adding it to camera's live feed  (void)processImage:(cv::Mat &)img { cv::Rect roi( cv::Point(100, 100), cv::Size(gtpl.size()));//Creating rect on which image will be mapped cv::Mat destinationROI = img( roi ); cv::Mat channels[4]; split(gtpl, channels); gtpl.copyTo( destinationROI ); //Copying gtpl matrix onto cameras matrix. }
Image producing white background on camera.
As you can see the image's background is showing white but it is transparent.
I would appreciate your help. Thanks in advance.

How to combine split runs of spectral clustering for a huge affinity matrix
Leading up to the question
I have a 2D complex valued image with a short time series of values. I want to cluster similar pixels / segment the image. My first attempt was kmeans, but that really clustered according to the means (there is a distinction in mean values, especially compared to surrounding voxels, but I suspect the temporal information is greater). My second attempt was ICA and then look at the k components with the largest magnitude, and that did successfully identify certain regions in my image as being different, but did not identify the group of pixels I was interested in (visually it is not hard to recognize them, but they are small).
Current situation
So because my first two tries did not work out, I looked around with google and it seemed spectral clustering might be appropriate. But I have some serious issues when using the method, mostly to do with limited available memory. I then thought, since I have so many pixels, I can just apply spectral clustering to seperate slabs of the data.
Question
My question has 2 parts:
1. How do I combine the results for the seperate segments? The eigenvectors are different and the cluster numbers are different. The result looks like it worked in the seperate slabs.
2. No distance / affinity between pixels in seperate slabs is taken into account. Can I make 'slabs between slabs'? For those slabs L and A are not symmetric, no clue how to perform the method then.
(3. Is there a similar or better method that does not need so much memory. Computation time is also borderline acceptable, easily exploding)
Perhaps I can somehow compare / merge all eigenvectors at the end?
I did not think my thata was that large. It is just a short timeseries of a complex image, with a pretty small number of pixels. Compared to HD or 4K video my data is tiny. Since all real world machines around us process so much more data, and my computer is not that bad, I suspect my computer should easily be able to cluster these pixels.
% generate data tempdisk = strel('disk',922/2); tempdisk = double(repmat((1+sqrt(1)).*tempdisk.Neighborhood,[1 1 15])); tempnoise = (rand(921,921,15)+sqrt(1).*rand(921,921,15))./10; tempim1 = double(imresize(mean(imread('cameraman.tif'),3),[921,921])); tempim1 = repmat(tempim1./max(tempim1(:)),[1 1 15]); tempim2 = double(rgb2hsv(imread('fabric.png'))); tempim2 = imresize(tempim2(:,:,1),[921,921]); tempim2 = repmat(tempim2./max(tempim2(:)),[1 1 15]); sin1 = repmat(permute(sin(2.*pi.*(0:14)./15),[1 3 2]),[921 921 1]); cdat = (sin1.*tempim1.*exp(sqrt(1).*2.*pi.*sin1.*(tempim2.^2)).*tempdisk+tempnoise); %this is what the mean data looks like meanm = mean(abs(cdat),3); meanp = angle(mean(cdat,3)); figure; subplot(1,2,1); imshow(meanm,[]); title('mean magnitude'); subplot(1,2,2); imshow(meanp,[]); title('mean phase')
%get all pixel vectors in a single matrix cvect = reshape(permute(cdat, [3,1,2]), [15, 921*921]); %k means and eigs dont accept complex, so convert to real here? cvectT = [real(cvect);imag(cvect)]'; %lets say 10000 by 10000 matrices are still ok nvox = 10000; nslab = floor(length(cvectT)/nvox); nrest = rem(length(cvectT), nvox); % spectral clusetring according to http://ai.stanford.edu/~ang/papers/nips01spectral.pdf keig = 50;%how many eigenvectors needed? more is better affinity_sigma = 1;% i dont understand how to calculate this either tic for islab = (nslab+1):1:1; islab/nslab toc if islab>nslab voxrange = (1:nrest) + ((islab1)*nvox);; else voxrange = (1:nvox) + ((islab1)*nvox); end Aff = exp( squareform(pdist(cvectT(voxrange,:))).^2/(2*affinity_sigma^2) ); % affinity matrix Dsq = sparse(size(Aff,1),size(Aff,2)); %degree matrix for idiag=1:size(Aff,1) Dsq(idiag,idiag) = sum(Aff(idiag,:))^(1/2); end Lap = Dsq * Aff * Dsq; %normalize affinity matrix [eigVectors(voxrange,1:keig), eigValues] = eigs(Lap, keig); %eigenvectors of normalized aff mat normEigVectors(voxrange,1:keig) = eigVectors(voxrange,1:keig)./repmat(sqrt(sum(abs(eigVectors(voxrange,1:keig)).^2,2)), [1 keig]); %normalize rows of eigen vectors, normr only works on real numbers [idx,C,sumd,D] = kmeans([real(normEigVectors(voxrange,1:keig)),imag(normEigVectors(voxrange,1:keig))], 5); %k means on normalized eigenvecotrs idxval(voxrange) = idx; end idxim = reshape(idxval, [1280, 1280]); figure; imshow(idxim,[]) toc
The result looks like the method is working nicely, now its just the slabs that are the issue and that there are no crossslab clusters. This took my computer about 15 minutes. I reduced the number of eigenvalues and the image size for this example so it runs in an acceptable amount of time. I think that illustrates part of my problem.
Someone here also suggests clustering slabs first and then combine them, he then says 'at the end you will have the problem of recombining them and this problem can be solved easily'. The bits designated as 'easy' in explanations are hardly ever easy of course. He links to this paper, but that method does not process all the data in slabs. It rather excludes vectors that are not close to a principal component.

Image segementation of lost Visio file
I have some images that started out as Visio diagrams, but were only saved as JPEGs. Each image has a white background with clipart computers and networking equipment scattered around. There are also connecting lines and labels, but I can algorithmically erase them. An example would be the main image here, excluding the window decorations and tool palettes: https://www.topbestalternatives.com/wpcontent/uploads/2016/02/draw810x406.jpg
I would like to extract the subimages and save them as distinct files, along with each one's original bounding box, so I can approximately recreate the original Visio. Ideally this would be done by a standalong program, or a Python script. I wrote a Python script using PIL that uses the histogram function to find vertical and horizontal bands of white/line color and splits the image into smaller rectangles. It mostly works, but treats, for example, a circle of an odd number of devices as a single subimage.
I've spent a fair amount of time researching this, but neither Stack Overflow nor Wikipedia have been much help. Any ideas? Thanks!

How to apply 2D active contours (snakes) in 3D image?
I am trying to apply a snake method on a 3D image with no sucess. To my understanding, MATLAB's "activecontours" can be applied to 3D images but it seems that it fits a surface (balloon) into an object, instead of a single contour (snake). Or at least it seems to repeat the seed contour slice by slice, instead of fitting a single countour into a 3D object, because the end result is the whole 3D image segmented. I am looking for an active contour that has 3D awareness, as suggested by the following figure:
If the seed contour is the blue contour (slightly in perspective as to see it is a contour), I want the final snake to be the green one, as it fits the closest and easiest edge, instead of the red one, which would happen if I simply applied a 2D snake onto a slice of the 3D image coplanar with the seed contour. Thanks for your time!

Watershed markers selection
Hi i'm trying to get the markers from a gradient of a image. Something like this: Markers example:
But my code doesn't work propertly:
void seleccionSemillas(int umbral) { C_Matrix auxiliar(GradienteAuto.FirstRow(), GradienteAuto.LastRow(), GradienteAuto.FirstCol(), GradienteAuto.LastCol(), 255); int Eaux, L = 1; for (int i = GradienteAuto.FirstRow() + 1; i < GradienteAuto.LastRow(); i++) { for (int j = GradienteAuto.FirstCol() + 1; j < GradienteAuto.LastCol(); j++) { if (GradienteAuto(i, j) <= umbral) { Eaux = 1; /* PC = Pixel Central 8 vecinos 1, 11, 01, +1 0, 1 PC 0, +1 +1, 1+1, 0+1, +1 */ // Vecino superior izquierdo if (((i  1) >= GradienteAuto.FirstRow() && (i  1) <= GradienteAuto.LastRow() && (j  1) >= GradienteAuto.FirstCol() && (j  1) <= GradienteAuto.LastCol()) && Eaux == 1) { if (auxiliar(i  1, j  1) != 255) Eaux = auxiliar(i  1, j  1); } // Vecino superior else if (((i  1) >= GradienteAuto.FirstRow() && (i  1) <= GradienteAuto.LastRow() && (j) >= GradienteAuto.FirstCol() && (j) <= GradienteAuto.LastCol()) && Eaux == 1) { if (auxiliar(i  1, j) != 255) Eaux = auxiliar(i  1, j); } // Vecino superior derecho else if (((i  1) >= GradienteAuto.FirstRow() && (i  1) <= GradienteAuto.LastRow() && (j + 1) >= GradienteAuto.FirstCol() && (j + 1) <= GradienteAuto.LastCol()) && Eaux == 1) { if (auxiliar(i  1, j + 1) != 255) Eaux = auxiliar(i  1, j + 1); } //Vecino izquierdo else if (((i) >= GradienteAuto.FirstRow() && (i) <= GradienteAuto.LastRow() && (j  1) >= GradienteAuto.FirstCol() && (j  1) <= GradienteAuto.LastCol()) && Eaux == 1) { if (auxiliar(i, j  1) != 255) Eaux = auxiliar(i, j  1); } //Vecino derecho else if (((i) >= GradienteAuto.FirstRow() && (i) <= GradienteAuto.LastRow() && (j + 1) >= GradienteAuto.FirstCol() && (j + 1) <= GradienteAuto.LastCol()) && Eaux == 1) { if (auxiliar(i, j + 1) != 255) Eaux = auxiliar(i, j +1); } // Vecino inferior izquierdo else if (((i + 1) >= GradienteAuto.FirstRow() && (i + 1) <= GradienteAuto.LastRow() && (j  1) >= GradienteAuto.FirstCol() && (j  1) <= GradienteAuto.LastCol()) && Eaux == 1) { if (auxiliar(i + 1, j  1) != 255) Eaux = auxiliar(i + 1, j  1); } // Vecino inferior else if (((i + 1) >= GradienteAuto.FirstRow() && (i + 1) <= GradienteAuto.LastRow() && (j) >= GradienteAuto.FirstCol() && (j) <= GradienteAuto.LastCol()) && Eaux == 1) { if (auxiliar(i + 1, j) != 255) Eaux = auxiliar(i + 1, j); } // Vecino inferior derecho else if (((i + 1) >= GradienteAuto.FirstRow() && (i + 1) <= GradienteAuto.LastRow() && (j + 1) >= GradienteAuto.FirstCol() && (j + 1) <= GradienteAuto.LastCol()) && Eaux == 1) { if (auxiliar(i + 1, j + 1) != 255) Eaux = auxiliar(i + 1, j + 1); } if (Eaux != 1) { auxiliar(i, j) = Eaux; } else { auxiliar(i, j) = L; L++; } } } } double max = auxiliar.Max(); if (max > 255.0) { auxiliar.Stretch(0, 255); } ImgSemillas = C_Image(auxiliar);
}
My gradient image is:
But i get the following image (seeds):
I'm trying to do this with 8connected neighbours but i don't get the expected result.
What i'm doing wrong?

Watershed implementation in C++
I'm working in the watershed algortih in C++. I have implemented a source that i've found but i didn't get the expected results. I obtain:
[
But the result should be this:
[
I have charge the image .bmp into a matrix an then i obtain the Gradient of the image using the Sobel operator. My wathershed algorith now is:
void Watershed() { stack<punto> s; punto p, neighbour; C_Matrix prueba3 (Gradiente.FirstRow(), Gradiente.LastRow(), Gradiente.FirstCol(), Gradiente.LastCol(), 1); int auxU, auxV, Eaux, L=1; for (double g = Gradiente.Min(); g <= Gradiente.Max(); g++) { for (int i = Gradiente.FirstRow(); i <= Gradiente.LastRow(); i++) { for (int j = Gradiente.FirstCol(); j <= Gradiente.LastCol(); j++) { if (Gradiente(i, j) == g) { p.Guarda(i, j); s.push(p); } while (s.empty() == 0) { p = s.top(); s.pop(); auxU = p.x; auxV = p.y; Eaux = 1; // 8connectivity for (int i = 0; i < 8; i++) { if (i == 0) neighbour.Guarda(auxU  1, auxV  1); else if (i == 1) neighbour.Guarda(auxU, auxV  1); else if (i == 2) neighbour.Guarda(auxU + 1, auxV  1); else if (i == 3) neighbour.Guarda(auxU  1, auxV); else if (i == 4) neighbour.Guarda(auxU + 1, auxV); else if (i == 5) neighbour.Guarda(auxU  1, auxV + 1); else if (i == 6) neighbour.Guarda(auxU, auxV + 1); else neighbour.Guarda(auxU + 1, auxV + 1); if (neighbour.x >= Gradiente.FirstRow() && neighbour.x <= Gradiente.LastRow() && neighbour.y >= Gradiente.FirstCol() && neighbour.y <= Gradiente.LastCol()) { if (prueba3(neighbour.x, neighbour.y) > 0) { if (Eaux == 1) { Eaux = prueba3(neighbour.x, neighbour.y); } else if (prueba3(neighbour.x, neighbour.y) != Eaux) Eaux = 0; } } } if (auxU >= Gradiente.FirstRow() && auxU <= Gradiente.LastRow() && auxV >= Gradiente.FirstCol() && auxV <= Gradiente.LastCol()) { if (Eaux >= 0) { prueba3(auxU, auxV) = Eaux; } else { prueba3(auxU, auxV) = L; L++; } } else { C_Print("Se sale"); C_PrintNum("AuxU", auxU); C_PrintNum("AuxV", auxV); } } } } } C_PrintNum("L = ", L); double max = prueba3.Max(); if (max > 255.0) { prueba3.Stretch(0, 255); } aux = C_Image(prueba3);
}
I don't know where is the fail, maybe my source has mistakes.