Counting objects in image - count

I want to count no of objects in an image using open cv. I have a soybean image and now I want to count the soybean numbers. If possible please help me and let me know the counting algorithms.
Thanks and I look forward to hear from you.
Regards,
Sumon

Sumon,
There is no one algorithm for counting objects. It greatly depends on the image itself. Depending on the contrast of the beans to the background it may be possible to use a simple threshold then a labeling algorithm, or even just finding contours.
The threshold function in opencv is cvThreshold. The contour finding algorithm is cvFindContours using this you could count the number of contours found.
Also the blob library has many facilities for this type of machine vision applications including connected component labeling which is basically what you need here. The library's description I believe is already included in opencv. The description of it can be found here.
I could provide some more assistance if I knew a little more about the image.

Related

raster::gridDistance() fails on medium to large raster files

I have some moderate sized raster files (max size ~190 MB) that I would like to calculate grid distances for using raster::gridDistance()
I'm finding that the operation is slow and/or R crashes for the largest of my files. Please note: I'm not seeking memory management advice (e.g. maxing out memory.limit(), breaking into smaller rasters or pursuing parallel processing methods) as these are sidestepping my issue. If grid distances should not be attempted for 190+ MB size files, then I will just break the job into more manageable pieces.
The raster::gridDistance() documentation mentions that I can try to solve "errors in the case of complex objects spread over different chunks... by varying the chunk size, see function setOptions()" and that "Additional distance measures and options (directions, cost-distance) are available in the {gdistance} package", but I have been hesitant to pursue these without better understanding the limitations/considerations.
Thanks to this question R - terra::distance() equivalent of raster::gridDistance(..., origin = x, omit = y) I understand that there is an alternative method using terra::gridDistance(), but I am not able to discern if the operation is any more efficient or suitable for my needs than raster::gridDistance()
I haven't posted a reprex or session info as my question is really as follows:
Is terra::gridDistance() (or some other alternative like those offered by {gdistance}) really a more efficient (faster) or customizable way for calculating a grid distance using moderate-large raster files?
If not, what are considerations for changing how the grid distance is calculated (varying chunk size or other means) using raster::gridDistance() and setOptions()?
If there is interest, I can reformat my question so that it better fits guidelines with a reprex etc. Also, I am posting the question here rather than Geographic Information Systems because the original linked question was posted here.
I understand that there is an alternative method using terra::gridDistance(), but I am not able to discern if the operation is any more efficient or suitable for my needs
Well, did you try it? That could have been more efficient than writing a long question.
The help file does not mention the limitations that raster::gridDistance has, so you should be good to go. But note that the method was renamed to terra::gridDist()
The "terra" package is the replacement for "raster" package; so "terra" is the best starting point more generally, I think.

How to Transform Graph into Grid Map?

I'm making a program that implements procedural content generation (PCG) to create maps in a 2d game.
I use the graph data structure as the basis. then the graph will be transformed into a map like in the example image I attached.
with graph specifications as follows:
-vertex can have more than 4 edges
-allowed the formation of cycles in the graph
any suggestions on what method I can use to transform the graph to a 2d map in a grid with space-tight results?
thanks
Uh, that is a tough one. The first problem you will encounter is whether this is even possible for the graph you use. See more below for that specific topic.
Let's say we ignore the fact that your graph could be impossible to map to a grid. I faced the same issue in my Master's Thesis a few years back. (PDF available here; 3.4 World Generation; page 25). I tried to find an algorithm, that could generate my world from a graph structure but ultimately failed. I tried placing one element after the other and implemented some backtracking in case it got stuck. But in the end you're facing a similar complexity to calculating chess moves. At some point you know you messed up, but you don't know how many steps you should go back/reverse, before trying the next one. If you try to solve this by brute force, you're not going to have a good time. And I did not come up with good heuristics to solve it in an adequate time.
My solution: I decided in the end to go with AnswerSet Programming. You're basically not solving the problem with an algorithm, but you find a (more or less) elegant logical representation of your problem and let a logic solver (program specifically made to find a valid solution to your logical problem-representation) do the work. Have a look in my thesis about the details, it was a few years ago and I didn't use one since. I remember however, that this process was not easy and it took me a few days to find a good logical representation of my problem.
Another question to ask: Could you work on the grid directly? Or maybe on a graph structure representing a grid? In the end a grid is nothing else than a graph; every cell is a node and neighbouring connections are the edges. I have quite some experience in the field and would be happy to help you, if you'd like to share what you want to achieve with your generator. I have also a vast collection of resources about procedural generation, maybe you find something helpful there, too.
More on the planarity of a graph: For your graph to be mappable to a plane, it needs to be planar, and checking so is also not trivial. The easiest way - if I'm not mistaken - is to prove the existence of a non-planar sub-graph, e.g. the K5 (the smallest non-planar a complete graph) or K3,3 (the smallest non-planar complete bipartite graph). And even if your graph is planar, it is not necessarily guaranteed that you can put it on your grid.

Measuring deviation in a music waveform in R?

I have posted this question in the R tag but I am open to solutions in other languages.
Lets say you have some waveforms. The first is just a bar. It is completely horizontal so it has no deviation. The other waveforms look like these:
Now I am able to get these waveforms separated into a uniform box so that they are all the same pixel size and resolution. My first idea was to quantify the amount of whitespace within one of these uniform boxes that the waveform used up using the code found here:
Measuring whitespace in a jpeg
Now however I want to measure the deviation between waveforms. That is, how could I quantify how "jumpy" a waveform is? Looking at the picture above, the second waveform seems the most homogeneous, and the third waveform seems to display the most variation, but I am unsure about how to quantify this. Any suggestions would be greatly appreciated.
I would recommend starting by getting familiarized with the packages tuneR and seewave, you can import and extract a lot of parameters from these two packages. In particular you could use the function acustat from seewave, this is a worked example with data from the package
data(tico)
note <- cutw(tico, from=0.5, to=0.9, output="Wave")
a<-acoustat(note)
a will give you 10 acoustic parameters from the sound, you could also use other packages like soundecology, that also extract some other variables, in particular, the function acoustic_diversity measures sound complexity

How do programs like mathematica draw graphs and how can I make such a program?

I've been wondering how programs like mathematica and mathlab, and so on, plot graphs of functions so gracefully and fast. Can anyone explain to me how they do this and, furthermore, how I can do this? Is it related to an aspect or course in Computer Programming or Math? Which then?
Well, with some encouragement from belisarius, here's a my comment as an answer: try looking at matplotlib. From the home page:
matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. matplotlib can be used in python scripts, the python and ipython shell (ala MATLAB®* or Mathematica®†), web application servers, and six graphical user interface toolkits.
It was originally inspired by MATLAB's plotting capabilities, though it's grown a lot since then. It's solid software - and it's open source, under a BSD license, so not only can you read the source, you can hack on it and use it in whatever you like.
Another place you could look is gnuplot. It's not one of the common open source licenses, but it's certainly open source, with some permissions to modify and such.
Gnuplot is a portable command-line driven graphing utility for linux, OS/2, MS Windows, OSX, VMS, and many other platforms. The source code is copyrighted but freely distributed (i.e., you don't have to pay for it). It was originally created to allow scientists and students to visualize mathematical functions and data interactively, but has grown to support many non-interactive uses such as web scripting. It is also used as a plotting engine by third-party applications like Octave. Gnuplot has been supported and under active development since 1986.
It does 3D plotting as well, which matplotlib doesn't do, and it's been around a lot longer. The reason I thought of matplotlib first is that it's intended as a library for a higher-level language, not a stand-alone application, so I'm guessing it might a bit easier for you to read.
One other suggestion, just to get an idea of the sorts of things Mathematica is doing under the hood, is to look at the documentation for Plot. In particular, if you look at the available options, you can deduce things.
MaxRecursion Automatic the maximum number of recursive subdivisions allowed
Method Automatic the method to use for refining curves
PerformanceGoal $PerformanceGoal aspects of performance to try to optimize
PlotPoints Automatic initial number of sample points
From the MaxRecursion and PlotPoints, you can see that it's doing an initial sampling then somehow deciding which regions need to be subdivided (resampled) to get an accurate view of the plot. And from there on, it's magic: there is some Method for this, and a PerformanceGoal to guide it...
For MATLAB, because of its cross-platform requirement there is no alternatives as using OpenGL. MATLAB runtime is written in C++ and non-axis GUI uses Java Swing. Therefore MATLAB Plot is probably a C++/OpenGL/Swing mixture.
In reality MATLAB graphics is much less complex then a video game graphics. I think it is easier to find tutorials on video game graphics and then "downsize" it to MATLAB functionality, like drawing a single line with the same color.
The most important concept is probably Transformation Matrix.
Basically most programs that plot any type of graph (particularly any graphs of reasonable complexity) will use some type of third party libraries.
The specific library used would depend on the programming language that is being used.
For example:
For a .Net application you might use Crystal reports. http://en.wikipedia.org/wiki/Crystal_Reports
For Java you might use JFreeChart. http://www.jfree.org/jfreechart/
And so on...
You will likely find numerious libraries for whatever language you decide to code in.
If you want to accomplish this functionality in your specific project I suggest using a library especially if you are a beginner. The internal complexities of how these graph libraries are implemented would be significant because of many issues such as cross platform compatibility, graphic rendering optimizations (ie: making sure the graphics render quickly and ‘prettily’), the maths associated with the positioning of elements on the graph and so forth.
Lastly I doubt you will find specific courses in this subject (or require them) as again excluding VERY specific cases programmers will always use libraries that already exist.
Why code it yourself when someone has
already solved the problem for you?
A good place to start is to understand that there is a grammar to graphics and what you want to construct upon receiving a plot command is a symbolic representation of the graph. For Mathematica, you can do something like
FullForm[Plot[Sin[x], {x, 0, 2 Pi}]]
to see the internal representation Mathematica uses. Basically you need to describe the line segments (2D) or meshes (3D) you want to draw in terms of their color and coordinates. Also, there needs to information about the scale of the graph and how to draw tick marks, label axes, etc.
This leads us to the heart of the question, how do you determine the line segment you want to draw from a function and a range? If you dig around in the help file for plot, you see a few things. First there is a plot points option and a MaxRecursion option. This leads me to believe (and this is just an educated guess, but it is how I would do it) that Mathematica plots the initial number of points on an even interval over the range to get a starting value. The next part is to identify regions where change exceeds some threshold and then to sample more points until the "change" between any two points in your line segment is below a threshold. Mathematica does this recursively, hence the MaxRecursion option.
So far I have been pretty vague about defining rate of change. A more useful way to describe change is to take 3 pts on your line segment. Assume a linear relationship between the 1st and 3rd point and, assuming this linear relationship, make a prediction about what the 2nd point would be. If the error of this prediction is sufficiently low, then consider the next group of three points. If the error is above a threshold, then you should sample some more points in this region until the threshold is met. In this way you will require relatively few points where the curve is relatively straight and more at the "interesting" parts where it bends in new directions. The smoothness of the curve you draw will be proportional to the error you are willing to tolerate in the linear prediction of points.

Finding Large Example Graphs

I am doing a project that involves processing large, sparse graphs. Does anyone know of any publicly available data sets that can be processed into large graphs for testing? I'm looking for something like a Facebook friend network, or something a little smaller with the same flavor.
I found the Stanford Large Network Dataset Collection pretty useful.
If you asked nicely, you might be able to get Brian O'Meara's data set for treetapper. It's a pretty nice example of real-world data in that genre. Particularly, you'd probably be interested in the coauthorship data.
http://www.treetapper.org/
http://www.brianomeara.info/
Github's API is nice for building out graphs. I've messed around using the python lib networkx to generate graphs of that network. Here's some sample code if you're interested.
Apologies for the double post, evidently I can only post two links at a time since I have <10 reputation...
DIMACS also has some data sets from their cluser challenge and there's always the Graph500. The Boost Graph Library has a number of graph generators as well.
Depending on what you consider "large", there's the University of Florida Sparse Matrix Collection as well as some DIMACS Road Networks (mostly planar of course).
A few other ones:
Newman's page
Barabasi's page
Pajek software
Arena's page
Network Science

Resources