ImageJ round method not working properly? - image-processing

I've been testing this for about an hour and I don't understand what's going on.
In imageJ, if I say:
i = 3.5;
print(round(i));
I get 4.
However, If I say:
print(65535/(27037-4777)*(26295-4777));
print(round(65535/(27037-4777)*(26295-4777)));
For some reason, I am getting:
63350.5
63350
Shouldnt it be rounding up to 63351?

Taking a look at your comments, the number that was generated through that calculation is actually 63350.499999..., and so when you try and round, the number gets rounded down and you get 63350. One thing that I can suggest is to add a small constant that may seem innocuous in hindsight, but it will resolve situations like this. You want to make it small enough so that it'll push the fractional part of your number over to the 0.5 range so it'll round successfully, but it won't interfere how round works for the other fractional parts.
The Java API has a function called Math.ulp that will compute the next possible fractional component that is after a particular floating point number that you specify. However, because ImageJ doesn't have this functionality, consider adding something small like 1e-5. This may seem like a foolish hack, but this will certainly avoid the situation like what you're experiencing now. This constant that you're adding should also not affect how round works in ImageJ.
tl;dr: Add a small constant to your number (like 1e-5) then round. This shouldn't affect how round works overall, and it'll simply push those numbers with a fractional component that are hovering at the 0.5 mark to be truly over 0.5.
Good luck!

Related

UIScrollView contentOffset not updating when changed

Seeing an odd issue surrounding changing a scroll view's content offset property.
I have a CADisplayLink that calls a method every frame. This method calculates how much to adjust the content offset by to produce an auto scroll type effect.
#objc private func tick() {
let fps = 1 / (displayLink.targetTimestamp - displayLink.timestamp)
let relativeAutoscrollAmount = autoscrollAmount / CGFloat(fps)
scrollView.contentOffset.x += relativeAutoscrollAmount
}
autoscrollAmount is a CGFloat property that represents how many pixels to move each second. On a 60Hz screen like an iPhone, this would mean a shift of 5/60 per invocation of that method, if this property is 5. However, the content offset never actually changes! Either visually or in memory, I can break and inspect it at any time and it's always 0!
Note that if I adjust it by 1 or greater each time, it works just fine. The animation is far to quick doing this, though.
Any thoughts?
EDIT: Obviously you can't actually adjust by less than a pixel at a time, but when I was doing this previously with a constraint constant, the system just calculated how to deal with this. (I assume by only moving every few ticks).
I believe I have the answer, or at the very least, an explanation based on a theory backed by some pretty good evidence. Here we go...
In the question, I provided an example of 5/60, where 5 is the amount of pixels to move per second, and 60 is the refresh rate of my screen. This comes out at approximately 0.083, which, as I said, caused no updates to contentOffset to take place.
At this point, I assumed that the minimum value was 1 (as you can't make changes to half a pixel) but this is in fact not the case. I began experimenting with different decimal values, in the hope of finding the threshold at which the updates to contentOffset stop taking place.
After a lot of trial and error, I found that value. It is 0.167. In my head, this had absolutely no significance whatsoever; but there obviously had to be something so I set about manipulating it in various ways to try to observe a pattern of some kind.
It soon became clear that 0.167 * 6 == 1, which although an interesting observation, again seemed to have little significance. That is until you note that the refresh rate of the display on my iPhone X that I was testing with is 60Hz, 10 times 6. At this point, I'm still stabbing blindly in the dark but this was at least a lead that I could explore a bit.
From this, I speculated that the system evaluates changes in layer's positions either every 6ms, or, perhaps more realistically, 10 times per display cycle. This supports the behaviour I am seeing in so far as if the movement value passes is too small (IE it cannot be represented in this 10 times per display cycle theorm), it is simply ignored.
This is quite a bold speculation so I decided to see if I could gather evidence to support the theory. I fired up my iPad pro which has a 120Hz display (as opposed to the 60Hz display on my iPhone X) to see if there was a trend. Sure enough, there was. The minimum value to see movement was now half what it was on the 60Hz screen. Given the greater refresh rate (double, in fact), and the original assumption of 10 updates per screen cycle, I am now seeing 20 updates per screen cycle, every 6ms, as before. There's definitely a relationship here.
Now I'd like to stress that this is all purely speculation, but at least I can sleep tonight having a good idea as to why this is happening! I'd love to hear other's thoughts, too.

Which is a better option for displaying irregular shapes in Swift?

let me start off by showing that I have this UIImageView set up in my ViewController:
Each one of the lines contains a UIButton for a body part. If I select a particular button, it will segue me appropriately.
What'd I like to do is, when the user taps (but doesn't release) the button, I'd like the appropriate body part to show like this:
I can achieve this using 2 options:
UIBuzierPath class to draw, but would take a lot of trial and error and many overlapping shapes per body part to get fitting nicely as similiar in a previous question: Create clickable body diagram with Swift (iOS)
Crop out the highlighted body parts from the original image and position it over the UIImageView depending on which UIButton selected. However there would only be one image per body part, but still less cumbersome then option 1.
Now, my question is not HOW to do it, but which would be a BETTER option for achieving this in terms of cpu processing and memory allocation?
In other words, I'm just concerned about my app lagging as well as taking up app size storage. I'm not concerned about how much time it takes to do it, I want to just make sure my app doesn't stutter when it tries to draw all the shapes.
Thanks.
It is very very very unlikely that either of those approaches would have any significant impact on CPU or memory. Particularly if in option 2, you just use the alpha channels of the cutout images and make them semitransparent tinted overlays. CPU/GPU-wise, neither of the approaches would drop you below the max screen refresh rate of 60fps (which is how users would notice a performance problem). Memory-wise, loading a dozen bezier paths or single-channel images into RAM should be a drop in the bucket compared to what you have available, particularly on any iOS device released in the last 5 years unless it's the Apple Watch.
Keep in mind that "premature optimization is the root of all evil". Unless you have seen performance issues or have good reason to believe they would exist, your time is probably better spent on other concerns like making the code more readable, concise, reusable, etc. See this brief section in Wikipedia on "When to Optimize": https://en.wikipedia.org/wiki/Program_optimization#When_to_optimize
Xcode have tests functionality built in(and performance tests too), so the best way is to try both methods for one body part and compare the results.
You may find the second method to be a bit slower, but not enough to be noticed by the user and at the same time a lot more easier to implement.
For quick start on tests here.
Performance tests here.

image segmentation when a characters connected in aforge and c#

I have the following image and has binarization。
i need to segmentation this image and recognized the digit.the double digits 4' and '9' that are connected together.
i read a some of document that mention about 'watershed morphology' method.the following image has be implemented a 'watershed segmentation'.
it's obvious that double 44 digits still connected but a 9 digit already segmentation to success.
i need some help how to segmentation a 44 characters!thanks.
zhengchun,
you need to understand that this is a quite difficult task which, in my opinion, cannot be perfectly solved in all cases.
In the first place, correctly splitting between characters without prior knowledge on their size and shape is just impossible: just consider the letter W, it could very well be split into two V's; on the opposite, nothing can tell you that two accidentally touching IJ are indeed two different letters rather then a U.
This means that no "blind" method like the watershed or any other can succeed, whatever the sophistication. Geometry alone is not enough, you need to rely on some description of the font (sizes and shapes).
To the best of my knowledge, you must let segmentation and recognition work together. What you can do is:
use the initial segmentation, hoping that touching and broken characters do not arise so often;
starting from the left, try immediate character recognition by splitting after one character width (you will need to try every font character in turn, possibly with different widths);
keep the most likely recognition result and continue recognition from that split, to the right;
if you expect broken characters, you can as well try recognitions that span two or more blobs and group these. (Gaps between blobs are good hints for splits, unless your characters can be broken or miss parts.)
You can improve the above procedure by adding heuristics to decide where splits are more likely, such as at a height minimum, but this is tricky. A pinch of black magic...

how to generate Tetris piece from a given grid

At first I think my question should have been asked before, but I didn't find what I want.
One element of this iOS app I'm developing is break a 8x8 grid into Tetris pieces (every piece is made of 4 blocks). Two particular question I have are:
what is the best way to represent a Tetris piece in objective-C?
what algorithm to present the grid into random Tetris pieces (and later on how to check if two pieces fits together).
Edition on 01/28
#livingtech, I think I implemented pretty much what you say, except the point of "having a hole". My code works with no hole at simple stage when Tetris block is two blocks only (yes, two squares, connected either horizontally or vertically), but at 3-square Tetris block, I would get holes. I just tested and out of 1000 running, I would get one without a hole. So definitely I need some mechanism to check if next square will be a singleton.
I been trying to do the same thing for my game. Though I am a total beginner, and I'm using XNA and C#.
But the way I'm trying to go about it is: 4x6 grid array
--y123456
X1-000000
X2-000000
X3-000000
X4-000000
Here,
0 signifies no block
1 defines a block
Algorithm
Start by taking the very first 0 in the array ( top left corner )
and randomly pick a 0 or a 1.
Randomly choose the coordinates based on x1/x2-y1/y2, decide 1 or 0.
If it is 1, then decide coordinated based on where that 1 was put.
If it was 1 on x2 y1, then decide if a 1 should go on next touching
coordinate.
If you just have to code in what coordinates touch and which don't,
and the logic will roll through.
I have mine set up bit different. But this is the basic foundation of my random Tetris engine.
I also found that making it like that really helps to have a whiteboard and make a drawing of the grid and label with your coordinates.
since ur board is 8*8, i think u can use a int64 to represent the board. each bit of the int64 represents whether the specific grid is filled or not.
Implementing Tetris is a hobby of mine. First implemented it in Windows/C. Then in Perl/Tk! Last implementation I did in Obj-C/Cocoa (Mac). In all cases, the game logic is the same. Only the UI stuff changes. I treat every little box separately and have a two-dimensional array which contains the presence (and color) of every "set" box on the board. Standard board size I use is 10 boxes wide by 20 boxes high.
Separately I keep track of the "dropping" piece: it's location and what kind of piece it is. Based on a timer, try to make the piece drop. If any of the boxes where the "dropping" piece would drop is already set, then stop dropping the piece and add the piece boxes to the "set" part of the board. Create a new piece, and start over.
It may not be the best way to implement it, but it makes sense in my head. From a pure OO perspective, each shape of a dropping piece could be a subclass of a generic shape class. Override functions that check whether the shape can drop, the offsets of the individual boxes in the shape, etc.
I don't think anybody has taken a stab at your question #2 yet here, so I'm going to outline what I would do.
Setup:
You'll need to represent your grid as an array of some kind. At the very least, you'll want some kind of boolean values, to denote whether each coordinate in the grid is "occupied".
You'll need to keep track of the pieces on your grid. This could be another array, this time holding references to the four coordinates for each piece.
You'll need a variable or variables to keep track of a coordinate in your grid where you'll start filling in pieces, (I would probably populate these with a corner to start).
Set up a "pool" of all possible Tetris pieces and rotations. (You'll want to keep track of which ones you've already checked on every iteration outlined below.)
Iterate:
Get a random piece from your pool that will fit into your starting coordinate. (If you want to get fancy, you could be smart about which ones you choose, or you could just go totally random. As pieces don't fit, mark them checked, so you don't keep checking randomly forever. If you get to a point where you've checked all the pieces, you have a solution that doesn't work, either back up an iteration, or start over.)
Make sure the Tetris piece you selected didn't leave a "hole", or empty space with less than 4 squares. (I don't know your requirements for solving this problem, so I can't say whether you should focus on speed or ease of coding, but you may be able to skip this step if you want, and "brute force" the solution.)
"Place" the piece, by writing it to your piece array and marking the coordinates filled.
Check for "finished" condition, in which all your spaces are filled.
Pick a new coordinate in your grid and repeat #1. (I would pick an empty one next to the previous coordinate.)
If this actual yet, I wrote test tetris app on Objective-C few months ago https://github.com/SonnyBlack/Test-Demo-Tetris . I think my algorithm not very well, but it working. =)

OpenCv Issue of Image Subtraction?

i am trying to subtract 2 image using the function cvAbsDiff(img1, img2, dest);
it working but sometimes when i bring my hand before my head or body the hand is not clear and background comes into picture... the background image(head) overlays my foreground.(hand)..
it works correctly on plain surfaces i.e when the background is even like a wall.
please check out my image...so that you can better understand my problem...!!!!
http://www.2shared.com/photo/hJghiq4b/bg_overlays_foreground.html
if you have any solution/hint please help me.......
There's nothing wrong with your code . Background subtraction is not a preffered way for motion detection or silhoutte detection because its not very robust.The problem is coming because both the background and the foreground are similar in colour at many regions which on subtractions pushes the foreground to back . You might try using
- optical flow for motion detection
- If your task is just detecting silhoutte or hand try training a HOG classifier over it
In case you do not want to try a new approach . You may try around playing with the threshold value(in your case 30).So when you subtract similar colour image there difference is less than 30 . And later you threshold with 30 so it just blacks out. Also you may try HSV or some other colourspace as well .
Putting in the relevant code would help. Also knowing what you're actually trying to achieve.
Which two images are you subtracting? I've done subtracting subsequent images (so, images taken with a delay of a fraction of a second), and the background subtraction generally results in the edges of moving objects, for example the edges of a hand, and not the entire silhouette of a hand. I'm guessing you're taking the difference of the current frame and a static startup frame. It's possible that parts aren't different enough (skin+skin).
I've got some computer problems tonight, I'll test it out tomorrow (pls put up at least the steps you actually carry thorough though) and let you know.
I'm still not sure what your ultimate goal is, although I'm guessing you want to do some gesture-recognition (since you have a vector called "fingers").
As Manpreet said, your biggest problem is robustness, and that is from the subjects having similar color.
I reproduced your image by having my face in the static comparison image, then moving it. If I started with only background, it was already much more robust and in anycase didn't display any "overlaying".
Quick fix is, make sure to have a clean subject-free static image.
Otherwise, you'll want to have dynamic comparison image, simplest would be comparing frame_n with frame_n-1. This will generally give you just the moving edges though, so if you want the entire silhouette you can either:
1) Use a different segmenting algorithm (what I recommend. Background subtraction is fast and you can use it to determine a much smaller ROI in which to search, and then use a different algorithm for more robust segmentation.)
2) Try to make a compromise between the static and dynamic comparison image, for example as an average of the past 10 frames or something like that. I don't know how well this works, but would be quite simple to implement, worth a try :).
Also, try with CV_THRESH_OTSU instead of 30 for your threshold value, see if you like that better.
Also, I noticed often the output flares (regions which haven't changed switch from black to white). Checking with the live stream, I'm quite certain it because of the webcam autofocusing/adjusting white balance etc.. If you're getting that too, turning off the autofocus etc. should help (which btw isn't done through openCV but depends on the camera. Possibly check this: How to programatically disable the auto-focus of a webcam?)

Resources