ColorBlob detection in an imageview in android - android

Assume that I have an image like this,
I want to draw contours around the roof and the wall. It may be achieved by color blob detection. There is a sample provided in Opencv 3.10, but its for camera view. I want it in an android imageView. Is there any way to achieve this?
Tried this code:
File imgFile = new File(Environment.getExternalStorageDirectory()+"/instahome/" + imgName);
if (imgFile.exists()) {
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
Log.d("heree",imgFile.getAbsolutePath().toString());
mRgba = new Mat(myBitmap.getHeight(), myBitmap.getWidth(), CvType.CV_8UC4);
ivw.setImageBitmap(myBitmap);
try {
detectEdges(myBitmap);
// contours(myBitmap);
}catch (Exception e)
{
Log.d("Error!!!", e.toString());
}
}
ivw.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int cols = mRgba.cols();
int rows = mRgba.rows();
int xOffset = (ivw.getWidth() - cols) / 2;
int yOffset = (ivw.getHeight() - rows) / 2;
int x = (int)event.getX() - xOffset;
int y = (int)event.getY() - yOffset;
Log.d(TAG, "Touch image coordinates: (" + x + ", " + y + ")");
if ((x < 0) || (y < 0) || (x > cols) || (y > rows)) return false;
Rect touchedRect = new Rect();
touchedRect.x = (x>4) ? x-4 : 0;
touchedRect.y = (y>4) ? y-4 : 0;
touchedRect.width = (x+4 < cols) ? x + 4 - touchedRect.x : cols - touchedRect.x;
touchedRect.height = (y+4 < rows) ? y + 4 - touchedRect.y : rows - touchedRect.y;
Mat touchedRegionRgba = mRgba.submat(touchedRect);
Mat touchedRegionHsv = new Mat();
Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL);
// Calculate average color of touched region
mBlobColorHsv = Core.sumElems(touchedRegionHsv);
int pointCount = touchedRect.width*touchedRect.height;
for (int i = 0; i < mBlobColorHsv.val.length; i++)
mBlobColorHsv.val[i] /= pointCount;
mBlobColorRgba = converScalarHsv2Rgba(mBlobColorHsv);
Log.d(TAG, "Touched rgba color: (" + mBlobColorRgba.val[0] + ", " + mBlobColorRgba.val[1] +
", " + mBlobColorRgba.val[2] + ", " + mBlobColorRgba.val[3] + ")");
mDetector.setHsvColor(mBlobColorHsv);
Imgproc.resize(mDetector.getSpectrum(), mSpectrum, SPECTRUM_SIZE);
mIsColorSelected = true;
if (mIsColorSelected) {
mRgba= new Mat(myBitmap.getHeight(), myBitmap.getWidth(), CvType.CV_8UC4);
mDetector.process(mRgba);
List<MatOfPoint> contours = mDetector.getContours();
Log.e(TAG, "Contours count: " + contours.size());
Imgproc.drawContours(mRgba, contours, -1, CONTOUR_COLOR);
Mat colorLabel = mRgba.submat(4, 68, 4, 68);
colorLabel.setTo(mBlobColorRgba);
Mat spectrumLabel = mRgba.submat(4, 4 + mSpectrum.rows(), 70, 70 + mSpectrum.cols());
mSpectrum.copyTo(spectrumLabel);
Bitmap newBitmap=Bitmap.createBitmap(myBitmap.getWidth(),myBitmap.getHeight(),myBitmap.getConfig());
try {
Utils.matToBitmap(mRgba,newBitmap);
}catch (Exception ex)
{
Log.d("error!", ex.toString());
}
ivw.setImageBitmap(newBitmap);
}
touchedRegionRgba.release();
touchedRegionHsv.release();
return false; // don't need subsequent touch events
}
});
addListeners();
addViews();
}
Searching around 5-6 hours, but no luck, any help will be appreciated!

Related

Android : How to put object on particular location of screen using openCv?

Edited:
If anyone one can suggest any link or post, I will be very grateful. I am trying to find solution from two days and i can't find any.Thank you in advance.
I am trying to put one object(image) on particular location of screen Using openCv in android.
I do have Points like this "{680.0, 488.0}" which is having (x,y) coordinate,
So how can I find particular location in my screen for putting object ?
Below is my code where i am getting Point:
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
mRgba = inputFrame.rgba();
mGray = inputFrame.gray();
iThreshold = minTresholdSeekbar.getProgress();
//Imgproc.blur(mRgba, mRgba, new Size(5,5));
Imgproc.GaussianBlur(mRgba, mRgba, new org.opencv.core.Size(3, 3), 1, 1);
//Imgproc.medianBlur(mRgba, mRgba, 3);
if (!mIsColorSelected) return mRgba;
List<MatOfPoint> contours = mDetector.getContours();
mDetector.process(mRgba);
Log.d(TAG, "Contours count: " + contours.size());
if (contours.size() <= 0) {
return mRgba;
}
RotatedRect rect = Imgproc.minAreaRect(new MatOfPoint2f(contours.get(0).toArray()));
double boundWidth = rect.size.width;
double boundHeight = rect.size.height;
int boundPos = 0;
for (int i = 1; i < contours.size(); i++) {
rect = Imgproc.minAreaRect(new MatOfPoint2f(contours.get(i).toArray()));
if (rect.size.width * rect.size.height > boundWidth * boundHeight) {
boundWidth = rect.size.width;
boundHeight = rect.size.height;
boundPos = i;
}
}
Rect boundRect = Imgproc.boundingRect(new MatOfPoint(contours.get(boundPos).toArray()));
//Core/Imgproc.rectangle( mRgba, boundRect.tl(), boundRect.br(), CONTOUR_COLOR_WHITE, 2, 8, 0 );
Log.d(TAG,
" Row start [" +
(int) boundRect.tl().y + "] row end [" +
(int) boundRect.br().y + "] Col start [" +
(int) boundRect.tl().x + "] Col end [" +
(int) boundRect.br().x + "]");
int rectHeightThresh = 0;
double a = boundRect.br().y - boundRect.tl().y;
a = a * 0.7;
a = boundRect.tl().y + a;
Log.d(TAG,
" A [" + a + "] br y - tl y = [" + (boundRect.br().y - boundRect.tl().y) + "]");
//Core.rectangle( mRgba, boundRect.tl(), boundRect.br(), CONTOUR_COLOR, 2, 8, 0 );
//Core/Imgproc.rectangle( mRgba, boundRect.tl(), new Point(boundRect.br().x, a), CONTOUR_COLOR, 2, 8, 0 );
MatOfPoint2f pointMat = new MatOfPoint2f();
Imgproc.approxPolyDP(new MatOfPoint2f(contours.get(boundPos).toArray()), pointMat, 3, true);
contours.set(boundPos, new MatOfPoint(pointMat.toArray()));
MatOfInt hull = new MatOfInt();
MatOfInt4 convexDefect = new MatOfInt4();
Imgproc.convexHull(new MatOfPoint(contours.get(boundPos).toArray()), hull);
if (hull.toArray().length < 3) return mRgba;
Imgproc.convexityDefects(new MatOfPoint(contours.get(boundPos).toArray()), hull, convexDefect);
List<MatOfPoint> hullPoints = new LinkedList<MatOfPoint>();
List<Point> listPo = new LinkedList<Point>();
for (int j = 0; j < hull.toList().size(); j++) {
listPo.add(contours.get(boundPos).toList().get(hull.toList().get(j)));
}
MatOfPoint e = new MatOfPoint();
e.fromList(listPo);
hullPoints.add(e);
List<MatOfPoint> defectPoints = new LinkedList<MatOfPoint>();
List<Point> listPoDefect = new LinkedList<Point>();
for (int j = 0; j < convexDefect.toList().size(); j = j + 4) {
Point farPoint = contours.get(boundPos).toList().get(convexDefect.toList().get(j + 2));
Integer depth = convexDefect.toList().get(j + 3);
if (depth > iThreshold && farPoint.y < a) {
listPoDefect.add(contours.get(boundPos).toList().get(convexDefect.toList().get(j + 2)));
}
Log.d(TAG, "defects [" + j + "] " + convexDefect.toList().get(j + 3));
}
MatOfPoint e2 = new MatOfPoint();
e2.fromList(listPo);
defectPoints.add(e2);
Log.d(TAG, "hull: " + hull.toList());
Log.d(TAG, "defects: " + convexDefect.toList());
Imgproc.drawContours(mRgba, hullPoints, -1, CONTOUR_COLOR, 3);
int defectsTotal = (int) convexDefect.total();
Log.d(TAG, "Defect total " + defectsTotal);
this.numberOfFingers = listPoDefect.size();
if (this.numberOfFingers > 5) {
this.numberOfFingers = 5;
} /*else if (this.numberOfFingers == 1) {
this.numberOfFingers = 0;
}
*/
mHandler.post(mUpdateFingerCountResults);
runOnUiThread(new Runnable() {
#Override
public void run() {
ring.setVisibility(View.VISIBLE);
/*LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(10,10);
ring.setLayoutParams(parms);*/
}
});
for (Point p : listPoDefect) {
Log.e("Points", p.toString());
// Imgproc.circle(mRgba, p, 6, new Scalar(255,0,255));
}
return mRgba;
}
Below is the method which i have used to save image and display. Now i need to put ring on one of captured hand fingers.
private void saveImage() {
if (MainActivity.listPoDefect.size() >= 5) {
mIsColorSelected = false;
if (listPoDefect.size() != 0) {
for (Point p :listPoDefect) {
Log.d(TAG, "before sorting X =" + String.valueOf(p.x) + " Y = " + String.valueOf(p.y));
}
Collections.sort(listPoDefect, new Comparator<Point>() {
public int compare(Point o1, Point o2) {
return Double.compare(o1.x, o2.x);
}
});
Log.d(TAG, "After Sorting ");
for (Point p : listPoDefect) {
Log.d(TAG, "after sorting X =" + String.valueOf(p.x) + " Y = " + String.valueOf(p.y));
}
}
mIsColorSelected = false;
Bitmap bitmap5 = Bitmap.createBitmap(mRgbaWithoutLine.cols(), mRgbaWithoutLine.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mRgbaWithoutLine, bitmap5);
bitmap = bitmap5;
//Create a new image bitmap and attach a brand new canvas to it
Bitmap tempBitmap = Bitmap.createBitmap(bitmap5.getWidth(), bitmap5.getHeight(), Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);
//Draw the image bitmap into the cavas
tempCanvas.drawBitmap(bitmap5, 0, 0, null);
double scaledWidth = bitmap5.getWidth();
double scaledHeight = bitmap5.getHeight();
double xScaleFactor = scaledWidth / bitmap5.getWidth();
double yScaleFactor = scaledHeight / bitmap5.getHeight();
Paint myRectPaint = new Paint();
myRectPaint.setStyle(Paint.Style.STROKE);
myRectPaint.setColor(Color.RED);
myRectPaint.setStrokeWidth(5);
myRectPaint.setAntiAlias(true);
//this is zeroth position manipulation
double differenceX= listPoDefect.get(2).x-listPoDefect.get(1).x;
double differenceY= listPoDefect.get(2).y-listPoDefect.get(1).y;
double zeroPostionX=listPoDefect.get(1).x-differenceX;
double zeroPostionY=listPoDefect.get(1).y-differenceY;
Point pointZeroths=listPoDefect.get(0);
Point pointNew=new Point(zeroPostionX,zeroPostionY);
listPoDefect.remove(0);
listPoDefect.add(0,pointNew);
double thirdPostionX=listPoDefect.get(2).x+differenceX;
double thirdPostionY=listPoDefect.get(2).y+differenceY;
Point thirdpointNew=new Point(thirdPostionX,thirdPostionY);
listPoDefect.remove(3);
listPoDefect.add(3,thirdpointNew);
// Point pointNewThird=new Point(pointthird.x+differenc,pointthird.y);
// HomeActivity.listPoDefect.remove(3);
// HomeActivity.listPoDefect.add(3,pointNewThird);
Paint paint_text = new Paint();
paint_text.setColor(Color.WHITE);
paint_text.setStyle(Paint.Style.FILL);
paint_text.setTextSize(30);
for (int row = 0; row < 4; row++) { // draw 2 rows
Point point1 = null;
point1 = listPoDefect.get(row);
android.graphics.Point canvas_point1 = new android.graphics.Point((int) ((point1.x * xScaleFactor)), (int) ((point1.y * yScaleFactor)));
Log.d(TAG, "after sorting canvas_point1 ="+"Raw ="+row +" " + String.valueOf(canvas_point1.x) + " Y = " + String.valueOf(canvas_point1.y));
Log.d(TAG, "====================================================================================================");
if(pointFListGraphies.size()!=4)
{
pointFListGraphies.add(new PointF(canvas_point1));
}
// tempCanvas.drawRect(canvas_point1.x, canvas_point1.y, canvas_point1.x + 130, canvas_point1.y + 50, myRectPaint);
// tempCanvas.drawText(String.valueOf(row+"-"+canvas_point1.x), canvas_point1.x, canvas_point1.y, paint_text);
}
Log.d(TAG, "====================================================================================================");
for (int row = 0; row < pointFListGraphies.size(); row++) { // draw 2 rows
PointF point1 = null;
point1 = pointFListGraphies.get(row);
Log.d(TAG, "=========pointF X="+point1.x +"poninF Y =" +point1.y);
}
tempbitmap = tempBitmap;
handImage.setVisibility(View.VISIBLE);
handImage.setImageBitmap(tempbitmap);
/* Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.ring);
tempCanvas.drawBitmap();*/
onCameraViewStopped();
//finish();
}
else {
}
}
Can anyone help me?
Thanks in advance.
OpenCV has a number of functions for writing on an image, which is usually what you are displaying on the screen.
FOr example the function to write text a particular location is
void cv::putText ( InputOutputArray img,
const String & text,
Point org,
int fontFace,
double fontScale,
Scalar color,
int thickness = 1,
int lineType = LINE_8,
bool bottomLeftOrigin = false
)
The parameters are:
Parameters
img Image.
text Text string to be drawn.
org Bottom-left corner of the text string in the image.
fontFace Font type, see cv::HersheyFonts.
fontScale Font scale factor that is multiplied by the font-specific base size.
color Text color.
thickness Thickness of the lines used to draw a text.
lineType Line type. See the line for details.
bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner.
You can find an overview of the drawing function here: https://docs.opencv.org/3.1.0/dc/da5/tutorial_py_drawing_functions.html
In your case, so long as your image covers the whole screen this allows you plot exactly where you want the text, or object or whatever you want too draw to appear.

Add border to ImageView Android for cropping

I want to add a rectangular border on my ImageView which allow users to change it's size from 8 directions to provide them a preview for cropping purpose.
Which way I can implement to achieve my purpose best, defining a custom ImageView and add code to draw rectangle or add ImageView to a SurfaceView?
Here is my code which I can use to draw a rectangle around my image:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.DragEvent;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
public class CustomCropImageView extends ImageView implements View.OnTouchListener{
// Bitmap to draw.
Bitmap myBitmap;
// Fundamental attributes.
int xPos, yPos;
int originWidth, originHeight;
int widthImg, heightImg;
int xCrop, yCrop;
int cropWidth, cropHeight;
GestureDetector myGesture;
public CustomCropImageView(Context context){
super(context);
xPos = yPos = xCrop = yCrop = 0;
// setOnTouchListener(this);
}
public CustomCropImageView(Context context, AttributeSet attSet){
super(context, attSet);
xPos = yPos = xCrop = yCrop = 0;
// setOnTouchListener(this);
}
#Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if(drawable == null)
return;
if(originWidth == 0 && originHeight == 0){
Bitmap tmp = ((BitmapDrawable)drawable).getBitmap();
myBitmap = tmp.copy(Bitmap.Config.ARGB_8888, true);
originWidth = myBitmap.getWidth();
originHeight = myBitmap.getHeight();
Integer[] myDWAndH = getScreenWidthAndHeight();
widthImg = cropWidth = myDWAndH[0];
heightImg = cropHeight = (int)((float)myDWAndH[0]*((float)originHeight / (float)originWidth));
yPos = yCrop = (myDWAndH[1] - heightImg) / 2;
myBitmap = Bitmap.createScaledBitmap(myBitmap, widthImg, heightImg, false);
}
Paint myPaint = new Paint();
canvas.drawBitmap(myBitmap, xPos, yPos, myPaint);
drawAnchorRectangle(canvas);
}
void drawAnchorRectangle(Canvas canvas){
// Anchor rectangle.
Paint myPaint = new Paint();
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setColor(getContext().getResources().getColor(R.color.ImgVBorder));
myPaint.setStrokeWidth(5);
Rect myRect = new Rect(xCrop, yCrop, cropWidth, yCrop + cropHeight);
canvas.drawRect(myRect, myPaint);
// Anchor point.
myPaint.setStyle(Paint.Style.FILL);
myPaint.setColor(getContext().getResources().getColor(R.color.ImgVAnchorPoint));
myPaint.setStrokeWidth(3);
int anchorPointW = 10;
int halfAnchorPointW = anchorPointW / 2;
/*
// Top left.
Rect anchorPoint = new Rect(xCrop + cropWidth - halfAnchorPointW, yCrop - halfAnchorPointW,
anchorPointW, yCrop + halfAnchorPointW);
canvas.drawRect(anchorPoint, myPaint);
// Top right.
anchorPoint.set(xCrop + cropWidth - halfAnchorPointW, yCrop - halfAnchorPointW,
anchorPointW, yCrop + halfAnchorPointW);
canvas.drawRect(anchorPoint, myPaint);
*/
}
Integer[] getScreenWidthAndHeight(){
DisplayMetrics dMetrics = new DisplayMetrics();
((MainActivity)getContext()).getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
Integer[] myResult = new Integer[2];
myResult[0] = dMetrics.widthPixels - 40;
myResult[1] = dMetrics.heightPixels;
return myResult;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getActionMasked();
final String TAG = "!!!123";
switch (action) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "Action was DOWN");
return true;
case MotionEvent.ACTION_MOVE:
Log.d(TAG, "Action was MOVE");
break;
case MotionEvent.ACTION_UP:
Log.d(TAG, "Action was UP");
break;
case MotionEvent.ACTION_CANCEL:
Log.d(TAG, "Action was CANCEL");
break;
case MotionEvent.ACTION_OUTSIDE:
Log.d(TAG, "Movement occurred outside bounds of current screen element");
break;
}
return super.onTouchEvent(event);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return super.onTouchEvent(event);
}
}
Here's how i solved, by defining a custom image view and make some change in OnDraw method, i also added code to reduce brightness of image so it looks nice with a background image behind the real when you resize the rectangle:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.DragEvent;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class CustomCropImageView extends ImageView implements View.OnTouchListener{
// Bitmap to draw.
Bitmap myBitmap;
// Fundamental attributes.
int xPos, yPos;
int originWidth, originHeight;
int widthImg, heightImg;
int xCrop, yCrop;
int cropWidth, cropHeight;
int offsetLeft = 0, offsetRight = 0, offsetTop = 0, offsetBottom = 0;
// List of anchor point rectangle.
List<Rect> anchorPoints;
int anchorPointW = 30;
int halfAnchorPointW = anchorPointW / 2;
// Background bitmap for cropping.
Bitmap darkBitmap;
public CustomCropImageView(Context context){
super(context);
xPos = yPos = xCrop = yCrop = 0;
// setOnTouchListener(this);
}
public CustomCropImageView(Context context, AttributeSet attSet){
super(context, attSet);
xPos = yPos = xCrop = yCrop = 0;
// setOnTouchListener(this);
}
Integer[] myDWAndH;
#Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if(drawable == null)
return;
if(originWidth == 0 && originHeight == 0){
Bitmap tmp = ((BitmapDrawable)drawable).getBitmap();
myBitmap = tmp.copy(Bitmap.Config.ARGB_8888, true);
originWidth = myBitmap.getWidth();
originHeight = myBitmap.getHeight();
myDWAndH = getScreenWidthAndHeight();
widthImg = cropWidth = myDWAndH[0] - anchorPointW;
heightImg = cropHeight = (int)((float)myDWAndH[0]*((float)originHeight / (float)originWidth)) - anchorPointW;
yPos = yCrop = (myDWAndH[1] - heightImg) / 2;
myBitmap = Bitmap.createScaledBitmap(myBitmap, widthImg, heightImg, false);
createDarkBitmap(myBitmap);
initAnchorPoint();
}
Paint myPaint = new Paint();
canvas.drawBitmap(darkBitmap, xPos + halfAnchorPointW, yPos + halfAnchorPointW, myPaint);
drawAnchorRectangle(canvas);
}
void drawAnchorRectangle(Canvas canvas){
// Anchor rectangle.
Paint myPaint = new Paint();
canvas.drawBitmap(myBitmap, new Rect(offsetLeft, offsetTop, cropWidth + offsetRight, cropHeight + offsetBottom),
new Rect(xCrop + halfAnchorPointW + offsetLeft, yCrop + halfAnchorPointW + offsetTop,
xCrop + halfAnchorPointW + cropWidth + offsetRight, yCrop + halfAnchorPointW + cropHeight + offsetBottom), myPaint);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setColor(getContext().getResources().getColor(R.color.ImgVBorder));
myPaint.setStrokeWidth(5);
Rect myRect = new Rect(xCrop + halfAnchorPointW + offsetLeft, yCrop + halfAnchorPointW + offsetTop,
xCrop + halfAnchorPointW + cropWidth + offsetRight, yCrop + halfAnchorPointW + cropHeight + offsetBottom);
canvas.drawRect(myRect, myPaint);
// Anchor point.
myPaint.setStyle(Paint.Style.FILL);
myPaint.setColor(getContext().getResources().getColor(R.color.ImgVAnchorPoint));
// Top left.
canvas.drawRect(anchorPoints.get(0), myPaint);
// Top right.
canvas.drawRect(anchorPoints.get(1), myPaint);
// Bottom left.
canvas.drawRect(anchorPoints.get(2), myPaint);
// Bottom right.
canvas.drawRect(anchorPoints.get(3), myPaint);
}
void initAnchorPoint(){
if(anchorPoints != null)
anchorPoints.clear();
else
anchorPoints = new ArrayList<>();
// Top left.
anchorPoints.add(new Rect(xCrop + offsetLeft, yCrop + offsetTop,
xCrop + anchorPointW + offsetLeft, yCrop + anchorPointW + offsetTop));
// Top right.
anchorPoints.add(new Rect(xCrop + cropWidth + offsetRight, yCrop + offsetTop,
xCrop + cropWidth + anchorPointW + offsetRight, yCrop + anchorPointW + offsetTop));
// Bottom left.
anchorPoints.add(new Rect(xCrop + offsetLeft, yCrop + cropHeight + offsetBottom,
xCrop + anchorPointW + offsetLeft, yCrop + cropHeight + anchorPointW + offsetBottom));
// Bottom right.
anchorPoints.add(new Rect(xCrop + cropWidth + offsetRight, yCrop + cropHeight + offsetBottom,
xCrop + cropWidth + anchorPointW + offsetRight, yCrop + cropHeight + anchorPointW + offsetBottom));
}
Integer[] getScreenWidthAndHeight(){
DisplayMetrics dMetrics = new DisplayMetrics();
((MainActivity)getContext()).getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
Integer[] myResult = new Integer[2];
myResult[0] = dMetrics.widthPixels - 40;
myResult[1] = dMetrics.heightPixels;
return myResult;
}
int anchorChoice = -1;
void setAnchorAction(MotionEvent event){
int x = (int)event.getRawX();
int y = (int)event.getRawY();
int offset = 50 + anchorPointW;
anchorChoice = -1;
if(y > (anchorPoints.get(0).top - offset) && y < (anchorPoints.get(0).bottom + offset)){
if(x < (anchorPoints.get(0).right + offset) && x > (anchorPoints.get(0).left - offset)){
anchorChoice = 0;
}
else if(x < (anchorPoints.get(1).right + offset) && x > (anchorPoints.get(1).left - offset))
anchorChoice = 1;
}
else if(y > (anchorPoints.get(2).top - offset) && y < (anchorPoints.get(2).bottom + offset)){
if(x < (anchorPoints.get(2).right + offset) && x > (anchorPoints.get(2).left - offset)){
anchorChoice = 2;
}
else if(x < (anchorPoints.get(3).right + offset) && x > (anchorPoints.get(3).left - offset))
anchorChoice = 3;
}
}
void resizeRectangle(MotionEvent event){
if(anchorChoice == -1)
return;
int x = (int)event.getRawX();
int y = (int)event.getRawY();
int dif = 0;
initAnchorPoint();
invalidate();
// xCrop + halfAnchorPointW + offsetLeft, yCrop + halfAnchorPointW + offsetTop,
// xCrop + halfAnchorPointW + cropWidth + offsetRight, yCrop + halfAnchorPointW + cropHeight + offsetBottom
int prevOLeft = offsetLeft;
int prevORight = offsetRight;
int prevOTop = offsetTop;
int prevOBottom = offsetBottom;
if(anchorChoice == 0){
offsetLeft = (x - xCrop - halfAnchorPointW);
offsetTop = (y - yCrop - halfAnchorPointW);
}
else if(anchorChoice == 1){
offsetRight = (x - xCrop - halfAnchorPointW - cropWidth);
offsetTop = (y - yCrop - halfAnchorPointW);
}
else if(anchorChoice == 2){
offsetLeft = (x - xCrop - halfAnchorPointW);
offsetBottom = (y - yCrop - halfAnchorPointW - cropHeight);
}
else if(anchorChoice == 3){
offsetRight = (x - xCrop - halfAnchorPointW - cropWidth);
offsetBottom = (y - yCrop - halfAnchorPointW - cropHeight);
}
// Boundaries.
// Left boundary.
if(xCrop + offsetLeft < xCrop)
offsetLeft = 0;
if(xCrop + halfAnchorPointW + cropWidth + offsetRight < xCrop + anchorPointW + offsetLeft)
offsetRight = prevORight;
// Top boundary.
if(yCrop + offsetTop < yCrop)
offsetTop = 0;
if(yCrop + halfAnchorPointW + cropHeight + offsetBottom < yCrop + anchorPointW + offsetTop)
offsetBottom = prevOBottom;
// Right boundary.
if(xCrop + halfAnchorPointW + cropWidth + offsetRight > xCrop + halfAnchorPointW + cropWidth)
offsetRight = 0;
if(xCrop + anchorPointW + offsetLeft > xCrop + halfAnchorPointW + cropWidth + offsetRight)
offsetLeft = prevOLeft;
// Bottom boundary.
if(yCrop + halfAnchorPointW + cropHeight + offsetBottom > yCrop + halfAnchorPointW + cropHeight)
offsetBottom = 0;
if(yCrop + anchorPointW + offsetTop > yCrop + halfAnchorPointW + cropHeight + offsetBottom)
offsetTop = prevOTop;
// End boundaries.
return;
}
void createDarkBitmap(Bitmap processedBitmap){
darkBitmap = Bitmap.createBitmap(processedBitmap.getWidth(), processedBitmap.getHeight(), Bitmap.Config.ARGB_8888);
int substractValue = 220;
for(int i = 0; i < processedBitmap.getWidth(); i++){
for(int j = 0; j < processedBitmap.getHeight(); j++){
int pixelToProcess = processedBitmap.getPixel(i, j);
// Get component infos.
int r = Color.red(pixelToProcess);
int g = Color.green(pixelToProcess);
int b = Color.blue(pixelToProcess);
int alpha = Color.alpha(pixelToProcess);
// Process component info.
alpha -= substractValue;
// alpha = alpha - substractValue;
darkBitmap.setPixel(i, j, Color.argb(alpha, r, g, b));
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getActionMasked();
final String TAG = "!!!123";
switch (action) {
case MotionEvent.ACTION_DOWN:
setAnchorAction(event);
Log.d(TAG, "" + anchorChoice);
return true;
case MotionEvent.ACTION_MOVE:
resizeRectangle(event);
break;
case MotionEvent.ACTION_UP:
Log.d(TAG, "Action was UP");
break;
case MotionEvent.ACTION_CANCEL:
Log.d(TAG, "Action was CANCEL");
break;
case MotionEvent.ACTION_OUTSIDE:
Log.d(TAG, "Movement occurred outside bounds of current screen element");
break;
}
return super.onTouchEvent(event);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return super.onTouchEvent(event);
}
}

How to detect (Count) Hair from image using OpenCV?

I have try below code using OpenCV functions cvtColor,Canny and HoughLinesP but not able to get accurate result or not work in some cases.
private boolean opencvProcessCount(Uri picFileUri) {
hairCount = 0;
totalC = 0;
//Log.e(">>>>>>>>","count " + picFileUri);
try {
InputStream iStream = getContentResolver().openInputStream(picFileUri);
byte[] im = getBytes(iStream);
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inDither = true;
opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap image = BitmapFactory.decodeByteArray(im, 0, im.length);
Mat mYuv = new Mat();
Utils.bitmapToMat(image, mYuv);
Mat mRgba = new Mat();
Imgproc.cvtColor(mYuv, mRgba, Imgproc.COLOR_RGB2GRAY, 4);
Imgproc.Canny(mRgba, mRgba, 80, 90);
Mat lines = new Mat();
int threshold = 80;
int minLineSize = 30;
int lineGap = 100;
Imgproc.HoughLinesP(mRgba, lines, 1, Math.PI/180, threshold, minLineSize, lineGap);
for (int x = 0; x < lines.rows(); x++)
{
double[] vec = lines.get(x, 0);
double x1 = vec[0],
y1 = vec[1],
x2 = vec[2],
y2 = vec[3];
Point start = new Point(x1, y1);
Point end = new Point(x2, y2);
double dx = x1 - x2;
double dy = y1 - y2;
double dist = Math.sqrt (dx*dx + dy*dy);
totalC ++;
Log.e(">>>>>>>>","dist " + dist);
if(dist>300.d)
{
hairCount ++;
// Log.e(">>>>>>>>","count " + x);
Imgproc.line(mRgba, start, end, new Scalar(0,255, 0, 255),5);// here initimg is the original image.
}// show those lines that have length greater than 300
}
Log.e(">>>>>>>>",totalC+" out hairCount " + hairCount);
// Imgproc.
} catch (Throwable e) {
// Log.e(">>>>>>>>","count " + e.getMessage());
e.printStackTrace();
}
return false;
}
Below are sample images to count hair :
I think you will find this article interesting:
http://www.cs.ubc.ca/~lowe/papers/aij87.pdf
They take a 2D bitmap, apply canny edge detector and then regroup segments of the different edges based on how likely they belong to a same object - in this case hair (and give criterias for such regrouping).
I think you could use this to know how many objects there are on the image, and if the image contains only hair, then you'd have a count for hair.

Android surfaceView Block Scaling error Rendering

I have problem, with rendering blocks after reScalling (zoom in-out) whole thing in my game
(sorry with my eng syntax , cuz Eng not my native language)
first look at my video
>Error Rendering Video
there are problem , When it's rendering blocks after change blocks scale to some specific number
look at my code
GameLoopThread.java
public class GameLoopThread extends Thread {
static long FPS = 20;
private GameView view;
private boolean running = false;
public GameLoopThread ( GameView view ) {
this.view = view;
}
#Override
public void run () {
long ticksPS = 1000 / GameLoopThread.FPS; // 0.05 second (50) ;
long startTime;
long delayDelta = 0;
long tmpDelta = 0;
while (this.running) {
Canvas c = null;
startTime = System.currentTimeMillis();
try {
c = this.view.getHolder().lockCanvas();
synchronized (this.view.getHolder()) {
this.view.onDraw(c);
}
ClientCoreStatic.clientGear.updateWorlds();
}
catch (NullPointerException e) {
e.printStackTrace();
}
finally {
if (c != null) this.view.getHolder().unlockCanvasAndPost(c);
}
// 50
// sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
tmpDelta = (System.currentTimeMillis() - startTime);
// time use Should below than 50
try {
if (tmpDelta > ticksPS) delayDelta += tmpDelta - ticksPS;
// d.pl("gameloop thread + " + delayDelta);
if (delayDelta > 0) {
//Thread.sleep(10);
if (ticksPS >= tmpDelta) {
delayDelta -= ticksPS - tmpDelta;
}
}
else {
delayDelta = 0;
Thread.sleep(ticksPS - tmpDelta);
}
if (this.view.hashCode() != ClientStatic.gameView.hashCode()) {
this.setRunning(false);
GameView.parentActivity.finish();
break;
}
}
catch (Exception e) {
e.printStackTrace();
d.pl("gameloop error");
}
}
}
GameView.java
#Override
public boolean onTouchEvent ( MotionEvent event ) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
// true
if (event.getPointerCount() == 1 ) {
if (GameView.spriteKeypadcircle.isCollition(
event.getX(),
event.getY()) == true) // d.pl("true..");
return true;
if (GameView.spriteBlocks.isCollition(event.getX(), event.getY())) {
// check
GameView.spriteBlocks.isCollitionOnBlock(event.getX(),event.getY());
d.pl("touching at "+ event.getX() + "," + event.getY());
return true;
}
}
if (event.getPointerCount() == 2 ) {
d.pl("distance 1 " +
GameView.distance1XY[0][0] +
"," +
GameView.distance1XY[0][1] +
" + " +
GameView.distance1XY[1][0] +
"," +
GameView.distance1XY[1][1] +
" | " +
GameView.distance2XY[0][0] +
"," +
GameView.distance2XY[0][1] +
" + " +
GameView.distance2XY[1][0] +
"," +
GameView.distance2XY[1][1]);
for (int size = event.getPointerCount(), i = 0; i < size; i++) {
// PointF point = mActivePointers.get(event.getPointerId(i));
// if (point != null) {
// point.x = event.getX(i);
// point.y = event.getY(i);
// }
float x = event.getX(i);
float y = event.getY(i);
if (!GameView.spriteBlocks.isCollition(x, y)) break;
GameView.distance2XY[i][0] = x;
GameView.distance2XY[i][1] = y;
} // for
// after get position
// check distance
double tmp1 = Math.sqrt((Math.pow(GameView.distance1XY[0][0] -
GameView.distance1XY[1][0], 2)) +
(Math.pow(GameView.distance1XY[0][1] -
GameView.distance1XY[1][1], 2)));
double tmp2 = Math.sqrt((Math.pow(GameView.distance2XY[0][0] -
GameView.distance2XY[1][0], 2)) +
(Math.pow(GameView.distance2XY[0][1] -
GameView.distance2XY[1][1], 2)));
GameView.newDistance = Math.abs(tmp1 - tmp2);
if (GameView.newDistance > 200) { // change too much
GameView.distance1XY[0][0] = GameView.distance2XY[0][0];
GameView.distance1XY[0][1] = GameView.distance2XY[0][1];
GameView.distance1XY[1][0] = GameView.distance2XY[1][0];
GameView.distance1XY[1][1] = GameView.distance2XY[1][1];
return true;
}
// if (newDistance < 100) break;
// if (newD < 100) break;
if (tmp1 < tmp2)
SpriteBlocks.viewScale += GameView.newDistance / 1000;
else
SpriteBlocks.viewScale -= GameView.newDistance / 1000;
if (SpriteBlocks.viewScale < 0.2) SpriteBlocks.viewScale = 0.2;
if (SpriteBlocks.viewScale > 10) SpriteBlocks.viewScale = 10;
GameView.spriteBlocks.updateScale();
GameView.distance1XY[0][0] = GameView.distance2XY[0][0];
GameView.distance1XY[0][1] = GameView.distance2XY[0][1];
GameView.distance1XY[1][0] = GameView.distance2XY[1][0];
GameView.distance1XY[1][1] = GameView.distance2XY[1][1];
return true;
}
return true;
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_UP:
return true;
}
return false;
}
#Override
protected void onDraw ( Canvas canvas ) {
canvas.drawColor(Color.GRAY);
GameView.spriteBlocks.onDraw(canvas);
GameView.spriteCharStand.onDraw(canvas);
GameView.spriteKeypadcircle.onDraw(canvas);
}
SpriteBlocks.java
public SpriteBlocks ( GameView gameView, Bitmap bmp ) {
this.bmp = bmp;
SpriteBlocks.width = bmp.getWidth() / SpriteBlocks.BMP_COLUMNS;
SpriteBlocks.height = bmp.getHeight() / SpriteBlocks.BMP_ROWS;
SpriteBlocks.widthPixels = Resources.getSystem().getDisplayMetrics().widthPixels;
SpriteBlocks.heightPixels = Resources.getSystem().getDisplayMetrics().heightPixels;
SpriteBlocks.centerXScreen = SpriteBlocks.widthPixels / 2;
SpriteBlocks.centerYScreen = SpriteBlocks.heightPixels / 2;
// System.out.println("fififi " + this.weightPixels + "," +
// this.heightPixels);
updateScale();
src2 = new Rect(0, 0, 400, 400);
paintTextPlayCur.setColor(Color.BLACK);
paintTextPlayCur.setTextSize(32);
paintTextSelectBlock.setColor(Color.RED);
paintTextSelectBlock.setTextSize(32);
}
public void updateScale () {
// SpriteBlocks.viewScale = 1;
SpriteBlocks.curBlockWidth = SpriteBlocks.viewScale *
SpriteBlocks.width;
SpriteBlocks.xBlockCount = Math.round(SpriteBlocks.widthPixels /
SpriteBlocks.curBlockWidth);
SpriteBlocks.yBlockCount = Math.round(SpriteBlocks.heightPixels /
SpriteBlocks.curBlockWidth);
SpriteCharStand.curPlayerRenderHeight = SpriteCharStand.playerRenderHeight *
SpriteBlocks.viewScale;
SpriteCharStand.curPlayerRenderWidth = SpriteCharStand.playerRenderWidth *
SpriteBlocks.viewScale;
SpriteCharStand.playerLeftTopX = SpriteBlocks.centerXScreen -
(SpriteCharStand.curPlayerRenderWidth / 2);
SpriteCharStand.playerLeftTopY = SpriteBlocks.centerYScreen -
(SpriteCharStand.curPlayerRenderHeight / 2);
SpriteCharStand.playerRightDownX = SpriteBlocks.centerXScreen +
(SpriteCharStand.curPlayerRenderWidth / 2);
SpriteCharStand.playerRightDownY = SpriteBlocks.centerYScreen +
(SpriteCharStand.curPlayerRenderHeight / 2);
d.pl("viewScale = " +
SpriteBlocks.viewScale +
", width = " +
SpriteBlocks.curBlockWidth);
}
#Override
public void onDraw ( Canvas canvas ) {
update();
if (ClientStatic.minePlayer == null) {
ClientStatic.minePlayer = ClientStatic.playerList
.get(ClientStatic.mineID);
if (ClientStatic.playerList.get(ClientStatic.mineID) == null) {
d.pl(" uuuu " + ClientStatic.mineID);
return;
}
}
// center screen point is this location
minePlayerX = ClientStatic.minePlayer.getLocation().getX();// + 0.5;
minePlayerY = ClientStatic.minePlayer.getLocation().getY();// + 1;
double adderPoint = 0.1;
for ( double adder = 0 ; adder <= 1 ; adder += adderPoint) {
minePlayerX += adderPoint;
// left top of screen is this location
bX = ((minePlayerX) - (SpriteBlocks.xBlockCount / 2) - 1);
bY = ((minePlayerY) + (SpriteBlocks.yBlockCount / 2) + 1);
// right down of screen is this position
cX = ((minePlayerX) + (SpriteBlocks.xBlockCount / 2) + 1);
cY = ((minePlayerY) - (SpriteBlocks.yBlockCount / 2) - 1);
// (SpriteCharStand.curPlayerRenderWidth / 2)
Material me;
Block bbo;
leftXdiff = (minePlayerX * 100) % 100;
leftYdiff = (minePlayerY * 100) % 100;
/*
* leftXdiff = Math.abs(leftXdiff);
* leftYdiff = Math.abs(leftYdiff);
*/
// calculating them from scale
leftXdiff = (curBlockWidth * leftXdiff) / 100;
leftYdiff = (curBlockWidth * leftYdiff) / 100;
// d.pl("cur x " + minePlayerX + " |m " + leftXdiff + " |bx " + bX);
for (double xloop = bX; xloop <= cX; xloop++) { // loop all position X
//for (double yloop = bY; yloop >= cY; yloop--) { // loop all position
// Y
for (double yloop = 140.5 ; yloop == 140.5 ; yloop ++) {
// range Y
if ((yloop < 0) || yloop > (FixVariable.CHUNK_HEIGHT - 1)) {
continue;
}
// get block of that location
bbo = ClientStatic.minePlayer
.getLocation()
.getWorld()
.getBlockAt(((xloop)), ((yloop)));
me = Material.getMaterial(bbo.getTypeId());
srcX = me.getX(bbo.getData()) * SpriteBlocks.width;
srcY = me.getY(bbo.getData()) * SpriteBlocks.height;
srcKey = ((double) srcX * 10) + ((double) (srcY));
src = srcList.get(srcKey);
if (src == null) {
src = new Rect(srcX, srcY, srcX + SpriteBlocks.width, srcY +
SpriteBlocks.height);
srcList.put(srcKey, src);
}
// position to drawing
if (xloop == 5 && yloop == 140.5) {
d.pl("SPY!! " + tmpXPosition + " = " + xloop + " - " + bX + " ) * 200 -" + leftXdiff);
}
tmpXPosition = ((xloop - bX) * SpriteBlocks.curBlockWidth) -
(leftXdiff );
if (xloop == 5 && yloop == 140.5) {
if (me != Material.BED){
d.pl("bed is spy");
}
if (Math.abs(lastTmpXPosition- tmpXPosition) < 1 &&
(Math.abs(lastTmpXPosition- tmpXPosition) > 0)) {
System.out.println("WT " + (Math.abs(lastTmpXPosition- tmpXPosition)));
}
d.pl("lastTmpXPos = " + lastTmpXPosition + " | " + tmpXPosition);
if (lastTmpXPosition != tmpXPosition) {
lastTmpXPosition = tmpXPosition;
}
}
tmpYPosition = (((SpriteBlocks.yBlockCount) - (yloop - cY + (10*adder) )) * SpriteBlocks.curBlockWidth) +
(leftYdiff);
if (dst == null) {
dst = new Rect();
}
dst.set(
(int) tmpXPosition,
(int) tmpYPosition,
(int) (tmpXPosition + SpriteBlocks.curBlockWidth),
(int) (tmpYPosition + SpriteBlocks.curBlockWidth));
canvas.drawBitmap(bmp, src, dst, null);
dst2.set(
(int) (tmpXPosition),
(int) (tmpYPosition),
(int) (tmpXPosition + SpriteBlocks.curBlockWidth),
(int) (tmpYPosition + SpriteBlocks.curBlockWidth));
canvas.drawBitmap(GameView.bmpRect, src2, dst2, null);
// break;
}
} // for
bbo = ClientStatic.minePlayer
.getLocation()
.getWorld()
.getBlockAt(
ClientStatic.minePlayer.getLocation().getX(),
ClientStatic.minePlayer.getLocation().getY());
me = Material.getMaterial(bbo.getTypeId());
srcX = me.getX(bbo.getData()) * SpriteBlocks.width;
srcY = me.getY(bbo.getData()) * SpriteBlocks.height;
srcKey = ((double) srcX * 10) + ((double) (srcY));
tmpXPosition = 5;
tmpYPosition = 5;
dst.set(
(int) tmpXPosition,
(int) tmpYPosition,
(int) (tmpXPosition + SpriteBlocks.curBlockWidth),
(int) (tmpYPosition + SpriteBlocks.curBlockWidth));
canvas.drawText(
"playLoc " +
ClientStatic.minePlayer.getLocation().getX() +
"," +
ClientStatic.minePlayer.getLocation().getY(),
200,
200,
paintTextPlayCur);
canvas.drawBitmap(bmp, src, dst, null);
canvas.drawText(
"block " +
ClientStatic.minePlayer
.getLocation()
.getWorld()
.getBlockAt(
ClientStatic.minePlayer
.getLocation()
.getX(),
ClientStatic.minePlayer
.getLocation()
.getY())
.getTypeId() +
" | chunk " +
ClientStatic.minePlayer
.getLocation()
.getWorld()
.getChunkAt(
ClientStatic.minePlayer
.getLocation()
.getX())
.getChunkNumberX() +
" | " +
ClientStatic.minePlayer
.getLocation()
.getWorld()
.getChunkAt(
ClientStatic.minePlayer
.getLocation()
.getX()).getX()
,
200,
300,
paintTextPlayCur);
canvas.drawBitmap(bmp, src, dst, null);
// draw touch block
if (blockTouching != null) {
canvas.drawText("touch " +
blockTouching.getX() +
"," +
blockTouching.getY() +
" = " +
blockTouching.getTypeId() +
":" +
blockTouching.getData()
, 300, 400, paintTextSelectBlock);
}
} // adder
}

Android Bitmap remove white margin

I've got a question regarding Bitmaps in Android: I 've got a Bitmap with white margins [size unknown] around. Is it possible to create a new Bitmap with all the white margins removed (rectangular shape)?
Bitmap bmp = Bitmap.createBitmap(width, bmpheigth, Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
canvas.setBitmap(bmp);
canvas.drawColor(Color.WHITE);
// draw here things!
It is asumed to be unknown where are things painted.
What is a good way to do that?
thanks!
Thanks #Maxim Efimov & #StackOverflowException
Just in Case Someone will need a snippet for this kind of problems:
this method returns a cut out smaller Bitmap with Margins removed. passing the pixels to a int-array first and then working with the array is a bit faster than the Bitmap.getPixel method
just call the method indicating Source Bitmap and Background color.
Bitmap bmp2 = removeMargins(bmp, Color.WHITE);
private static Bitmap removeMargins2(Bitmap bmp, int color) {
// TODO Auto-generated method stub
long dtMili = System.currentTimeMillis();
int MTop = 0, MBot = 0, MLeft = 0, MRight = 0;
boolean found1 = false, found2 = false;
int[] bmpIn = new int[bmp.getWidth() * bmp.getHeight()];
int[][] bmpInt = new int[bmp.getWidth()][bmp.getHeight()];
bmp.getPixels(bmpIn, 0, bmp.getWidth(), 0, 0, bmp.getWidth(),
bmp.getHeight());
for (int ii = 0, contX = 0, contY = 0; ii < bmpIn.length; ii++) {
bmpInt[contX][contY] = bmpIn[ii];
contX++;
if (contX >= bmp.getWidth()) {
contX = 0;
contY++;
if (contY >= bmp.getHeight()) {
break;
}
}
}
for (int hP = 0; hP < bmpInt[0].length && !found2; hP++) {
// looking for MTop
for (int wP = 0; wP < bmpInt.length && !found2; wP++) {
if (bmpInt[wP][hP] != color) {
Log.e("MTop 2", "Pixel found #" + hP);
MTop = hP;
found2 = true;
break;
}
}
}
found2 = false;
for (int hP = bmpInt[0].length - 1; hP >= 0 && !found2; hP--) {
// looking for MBot
for (int wP = 0; wP < bmpInt.length && !found2; wP++) {
if (bmpInt[wP][hP] != color) {
Log.e("MBot 2", "Pixel found #" + hP);
MBot = bmp.getHeight() - hP;
found2 = true;
break;
}
}
}
found2 = false;
for (int wP = 0; wP < bmpInt.length && !found2; wP++) {
// looking for MLeft
for (int hP = 0; hP < bmpInt[0].length && !found2; hP++) {
if (bmpInt[wP][hP] != color) {
Log.e("MLeft 2", "Pixel found #" + wP);
MLeft = wP;
found2 = true;
break;
}
}
}
found2 = false;
for (int wP = bmpInt.length - 1; wP >= 0 && !found2; wP--) {
// looking for MRight
for (int hP = 0; hP < bmpInt[0].length && !found2; hP++) {
if (bmpInt[wP][hP] != color) {
Log.e("MRight 2", "Pixel found #" + wP);
MRight = bmp.getWidth() - wP;
found2 = true;
break;
}
}
}
found2 = false;
int sizeY = bmp.getHeight() - MBot - MTop, sizeX = bmp.getWidth()
- MRight - MLeft;
Bitmap bmp2 = Bitmap.createBitmap(bmp, MLeft, MTop, sizeX, sizeY);
dtMili = (System.currentTimeMillis() - dtMili);
Log.e("Margin 2",
"Time needed " + dtMili + "mSec\nh:" + bmp.getWidth() + "w:"
+ bmp.getHeight() + "\narray x:" + bmpInt.length + "y:"
+ bmpInt[0].length);
return bmp2;
}
Use Bitmap.createBitmap(source, x, y, width, height) so knowing the white margin size you can do what you want.
My solution:
private Bitmap trim(Bitmap bitmap, int trimColor){
int minX = Integer.MAX_VALUE;
int maxX = 0;
int minY = Integer.MAX_VALUE;
int maxY = 0;
for(int x = 0; x < bitmap.getWidth(); x++){
for(int y = 0; y < bitmap.getHeight(); y++){
if(bitmap.getPixel(x, y) != trimColor){
if(x < minX){
minX = x;
}
if(x > maxX){
maxX = x;
}
if(y < minY){
minY = y;
}
if(y > maxY){
maxY = y;
}
}
}
}
return Bitmap.createBitmap(bitmap, minX, minY, maxX - minX + 1, maxY - minY + 1);
}
It isn't very fast, for 1280 x 576 px bitmap execution took 2965ms on Xiaomi Redmi 3S.
If it possible scale down image before triming:
private Bitmap scaleDown(Bitmap bitmap, float maxImageSize, boolean filter) {
float ratio = Math.min(maxImageSize / bitmap.getWidth(), maxImageSize / bitmap.getHeight());
int width = Math.round(ratio * bitmap.getWidth());
int height = Math.round(ratio * bitmap.getHeight());
return Bitmap.createScaledBitmap(bitmap, width, height, filter);
}
Late to the party, but this variation is a bit faster and perhaps easier to read:
public static Bitmap imageWithMargin(Bitmap bitmap, int color, int maxMargin) {
int maxTop = 0, maxBottom = 0, maxLeft = 0, maxRight = 0;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] bitmapArray = new int[width * height];
bitmap.getPixels(bitmapArray, 0, width, 0, 0, width, height);
// Find first non-color pixel from top of bitmap
searchTopMargin:
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (bitmapArray[width * y + x] != color) {
maxTop = y > maxMargin ? y - maxMargin : 0;
break searchTopMargin;
}
}
}
// Find first non-color pixel from bottom of bitmap
searchBottomMargin:
for (int y = height - 1; y >= 0; y--) {
for (int x = width - 1; x >= 0; x--) {
if (bitmapArray[width * y + x] != color) {
maxBottom = y < height - maxMargin ? y + maxMargin : height;
break searchBottomMargin;
}
}
}
// Find first non-color pixel from left of bitmap
searchLeftMargin:
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (bitmapArray[width * y + x] != color) {
maxLeft = x > maxMargin ? x - maxMargin : 0;
break searchLeftMargin;
}
}
}
// Find first non-color pixel from right of bitmap
searchRightMargin:
for (int x = width - 1; x >= 0; x--) {
for (int y = height - 1; y >= 0; y--) {
if (bitmapArray[width * y + x] != color) {
maxRight = x < width - maxMargin ? x + maxMargin : width;
break searchRightMargin;
}
}
}
return Bitmap.createBitmap(bitmap, maxLeft, maxTop, maxRight - maxLeft, maxBottom - maxTop);
}

Categories

Resources