I'm creating a list of ImageView in my android app with negative margins set for each.
I'm using this to convert dp to pixels:
public int dpToPixel(float dp) {
DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
return (int)((dp * displayMetrics.density) + 0.5);
}
And the List is like this:
List<GridLayout> columnNLinesGrid = new ArrayList<GridLayout>();
List<ImageView> columnLines = new ArrayList<ImageView>();
for (int i = 1; i <= rowLayoutsCount; i++) {
columnNLinesGrid.add(new GridLayout(this));
GridLayout.LayoutParams colGridParam = new GridLayout.LayoutParams();
colGridParam.setMargins(0,0,0,0);
colGridParam.topMargin = dpToPixel(-10);
columnNLinesGrid.get(i - 1).setLayoutParams(colGridParam);
columnNLinesGrid.get(i - 1).setColumnCount(columnLayoutsCount);
linearLayouts.get(i - 1).addView(columnNLinesGrid.get(i - 1));
for (int j = 1; j <= columnLayoutsCount; j++) {
columnLines.add(new ImageView(this));
GridLayout.LayoutParams lineParam = new GridLayout.LayoutParams();
lineParam.rowSpec = GridLayout.spec(0);
lineParam.columnSpec = GridLayout.spec(j - 1);
if(j-1>0){
lineParam.leftMargin = (int) dpToPixel(23);
} else{
lineParam.leftMargin = 0;
}
lineParam.width = GridLayout.LayoutParams.WRAP_CONTENT;
lineParam.height = (int) dpToPixel(35);
columnLines.get(colLinesCount).setLayoutParams(lineParam);
columnLines.get(colLinesCount).setImageResource(R.drawable.linevert);
columnNLinesGrid.get(i - 1).addView(columnLines.get(colLinesCount));
colLinesCount++;
}
}
It seems like colGridParam.topMargin = dpToPixel(-10) is not working. I tried negative margins in some other cases and neither of them worked.
Related
I'm writing a fairly simple app that will, in real-time, tell the user how many pixels there are above a certain color value in an image.
That is, it takes preview images from the camera and analyses them as the user move the camera around.
Right now, I have this code, which technically works:
mRgba = inputFrame.rgba();
Rect sample = new Rect();
Mat sampleRegionRgba;
numPixs = 0;
boundary.add(100); boundary.add(100);boundary.add(100);
int cols = mRgba.cols();
int rows = mRgba.rows();
double yLow = (double)mOpenCvCameraView.getHeight() * 0.2401961;
double yHigh = (double)mOpenCvCameraView.getHeight() * 0.7696078;
double xScale = (double)cols / (double)mOpenCvCameraView.getWidth();
double yScale = (double)rows / (yHigh-yLow);
int tmpX;
int tmpY;
for (int x = 0; x < cols-6; x++) {
for (int y = (int)yLow; y < yHigh-6; y++){
tmpX = (int)((double)x * xScale);
tmpY = (int)((double)y * yScale);
sample.x = tmpX+3;
sample.y = tmpY+3;
sample.width = 2;
sample.height = 2;
sampleRegionRgba = mRgba.submat(sample);
Mat sampleRegionHsv = new Mat();
Imgproc.cvtColor(sampleRegionRgba, sampleRegionHsv, Imgproc.COLOR_RGB2HSV_FULL);
mBlobColorHsv = Core.sumElems(sampleRegionHsv);
int pointCount = sample.width * sample.height;
for (int i = 0; i < mBlobColorHsv.val.length; i++){
mBlobColorHsv.val[i] /= pointCount;
}
mBlobColorRgba = convertScalarToRgba(mBlobColorHsv);
// System.out.println(mBlobColorRgba.toString());
if (mBlobColorRgba.val[0] > boundary.get(0)
&& mBlobColorRgba.val[1] > boundary.get(1)
&& mBlobColorRgba.val[2] > boundary.get(2)){
numPixs += 1;
}
// System.out.println(sampleRegionRgba.toString());
}
}
System.out.println("number of pixels above boundary: "+Integer.toString(numPixs));
massflow = m*(Math.pow(numPixs,.25))+b;
runOnUiThread(new Runnable() {
#Override
public void run() {
massflow_text.setText("Massflow: "+Double.valueOf(massflow));
}
});
While this code works, it takes about 6 seconds to run for each image.
I'd like it to have a much more reasonable frame rate. I know this can be done with numpy (I've done it with np.where()). Is it possible with Java/OpenCv/Android Studio ?
In my project, I'm creating tables dynamically. Each table is a weekly schedule for college students. So, each cell has an String in it. My working code is below;
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
TableLayout.LayoutParams tableLayoutParams = new TableLayout.LayoutParams();
TableLayout tableLayout = new TableLayout(this);
tableLayout.setBackgroundColor(Color.BLACK);
// 2) create tableRow params
TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams(width/9,height/12);
tableRowParams.setMargins(1, 1, 1, 1);
tableRowParams.weight = 1;
for(int m=0;m<major.size();m++) {
for (int i = 0; i <rowCount; i++) {
// 3) create tableRow
TableRow tableRow = new TableRow(this);
tableRow.setBackgroundColor(Color.BLACK);
for (int j = 0; j <columnCount; j++) {
// 4) create textView
TextView textView = new TextView(this);
textView.setBackgroundColor(Color.WHITE);
textView.setGravity(Gravity.CENTER);
WeeklySchedule ws=major.get(m);
String course;
if (i == 0 && j == 0) {
textView.setText(" ");
} else if (i == 0) {
textView.setText(cv[j-1]);
textView.setBackgroundColor(Color.GREEN);
} else if (j == 0) {
textView.setText(rv[i -1]); textView.setBackgroundColor(Color.GRAY);
} else if(j!=0&&i!=0){
if(ws.table[i-1][j-1].size()==2){
course=ws.table[i-1][j-1].get(0).getCourseCode()+"/"+ws.table[i-1][j-1].get(1).getCourseCode();
textView.setBackgroundColor(Color.RED);
}
else if(ws.table[i-1][j-1].size()==0){
course= " ";
}
else {
course=ws.table[i-1][j-1].get(0).getCourseCode();
}
textView.setText(course);
}
// 5) add textView to tableRow
tableRow.addView(textView, tableRowParams);
}
// 6) add tableRow to tableLayout
tableLayout.addView(tableRow, tableLayoutParams);
}
It is working but the result is like that;
here
How can i fixed column height and get rid of these black lines.
Please help!
Thanks a lot for advice
I want to move a sliding window (a Rect) by half of each window, but I can only get the first line:
My code:
int widthImg = 600;
int HeightImg = 500;
int wWin = 100;// weight window
int hWin = 100;// height window
int xWin = 0;
int yWin = 0;
int winSize = ((widthImg/wWin)*2) * ((HeightImg/hWin)*2);// slide half of window(50)
for(int i=0;i<winSize;i++){
Mat ROIMat = new Mat();
if(i < winSize){
xWin = xWin + wWin/2;
if(xWin == widthImg){
xWin = 0;
yWin = yWin + hWin/2;
}
}
ROIMat = croppMat(Highgui.imread(fileImageName), new Rect(xWin , yWin , wWin , hWin) );
Highgui.imwrite(pathROI+"\\"+i+".jpg", ROIMat); //save ROI image
}
ERROR:
OpenCV Error: Assertion failed (0 <= _colRange.start && _colRange.start <= _colRange.end && _colRange.end <= m.cols) in cv::Mat::Mat, file......\opencv\modules\core\src\matrix.cpp, line 292 Exception in thread "AWT-EventQueue-0" CvException [org.opencv.core.CvException: cv::Exception: ........\opencv\modules\core\src\matrix.cpp:292: error: (-215) 0 <= _colRange.start && _colRange.start <= _colRange.end && _colRange.end <= m.cols in function cv::Mat::Mat]
Where am I doing wrong?
If I understand correctly your question, you should correct your for loop.
Take a look at this code, and check if it's the expected result. The code is in C++, but it's be very close to Java, and I added as comments the equivalent Java calls (but I didn't test them).
#include <opencv2/opencv.hpp>
#include <string>
using namespace cv;
int main()
{
// Load image
Mat3b img = imread(fileImageName);
// JAVA: Mat img = Highgui.imread(fileImageName);
int widthImg = img.cols; // JAVA: img.cols();
int heightImg = img.rows; // JAVA: img.rows();
int wWin = 100; // weight window
int hWin = 100; // height window
int counter = 0;
for (int yWin = 0; yWin <= heightImg - hWin; yWin += hWin/2)
{
for (int xWin = 0; xWin <= widthImg - wWin; xWin += wWin/2)
{
Mat ROIMat(img(Rect(xWin, yWin, wWin, hWin)));
// JAVA: Mat ROIMat = new Mat();
// JAVA: ROIMat = croppMat(img, new Rect(xWin, yWin, wWin, hWin));
imwrite(pathROI + std::to_string(counter) + ".jpg", ROIMat);
//JAVA: Highgui.imwrite(pathROI + "\\" + counter + ".jpg", ROIMat); //save ROI image
++counter;
}
}
return 0;
}
I have created Mat with training images (150 images size of 144x33) so my Mat is 4752 width and 150 height. Another mat with labels is 1 width and 150 height. And now when I am trying svm.train() with these two Mat's, I am getting following error:
OpenCV Error: Bad argument (response #2 is not integral) in cvPreprocessCategoricalResponses, file ..\..\..\..\opencv\modules\ml\src\inner_functions.cpp, line 715
Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: ..\..\..\..\opencv\modules\ml\src\inner_functions.cpp:715: error: (-5) response #2 is not integral in function cvPreprocessCategoricalResponses]
Here is piece of my code, can somebody tell me what could be wrong?
Mat trainingImages = new Mat(0, imageWidth * imageHeight, CvType.CV_32FC1);
Mat labels = new Mat(amountOfPlates + amountOfNoPlates, 1, CvType.CV_32FC1);
List<Integer> trainingLabels = new ArrayList<>();
for (int i = 0; i < amountOfPlates; i++) {
int index = i + 1;
String file = pathPlates + index + ".jpg";
Mat img = Highgui.imread(file, 0);
img.convertTo(img, CvType.CV_32FC1);
img = img.reshape(1, 1);
trainingImages.push_back(img);
trainingLabels.add(1);
}
for (int i = 0; i < amountOfNoPlates; i++) {
int index = i + 1;
String file = pathNoPlates + index + ".jpg";
Mat img = Highgui.imread(file, 0);
img.convertTo(img, CvType.CV_32FC1);
img = img.reshape(1, 1);
trainingImages.push_back(img);
trainingLabels.add(0);
}
Integer[] array = trainingLabels.toArray(new Integer[trainingLabels.size()]);
int[] trainLabels = new int[array.length];
for (int i = 0; i < array.length; i++) {
trainLabels[i] = array[i];
}
for (int i = 0; i < trainingLabels.size(); i++) {
labels.put(i, 1, trainLabels[i]);
}
CvSVMParams params = new CvSVMParams();
params.set_svm_type(CvSVM.C_SVC);
params.set_kernel_type(CvSVM.LINEAR);
params.set_degree(0);
params.set_gamma(1);
params.set_coef0(0);
params.set_C(1);
params.set_nu(0);
params.set_p(0);
TermCriteria tc = new TermCriteria(opencv_core.CV_TERMCRIT_ITER, 1000, 0.01);
params.set_term_crit(tc);
Size data = trainingImages.size();
Size label = labels.size();
CvSVM svmClassifier = new CvSVM();
svmClassifier.train(trainingImages, labels, new Mat(), new Mat(), params);
svmClassifier.save("test.xml");
Size data shows: width = 4752, height = 150
Size labels shows: width = 1, height = 150
What am I doing wrong?
Mat labels was defined as CV_32FC1, but you extend it with integers from int[] trainLabels.
You should use floating point trainLabels or CV_32SC1 type labels instead.
I need help with setting a texture to a .MD2 model in java/android
According to wikipedia, I came up with the following: ( MD2 (file_format) )
Loading texCoords:
int idx = 0;
for(int i = 0; i < this.pHeader.num_st; i++) //num_st = Number of texture coordinates
{
this.fTexCoords[i][0] = (float)is.readShort(); //S
this.fTexCoords[i][1] = (float)is.readShort(); //T
}
and computing them:
int idx2 = 0;
int idx = 0;
for(int i = 0; i < this.pHeader.num_tris; i++) //num_tris = Number of triangles
{
this.fIndices[idx+0] = is.readUnsignedShort();
this.fIndices[idx+1] = is.readUnsignedShort();
this.fIndices[idx+2] = is.readUnsignedShort();
int uvID0 = is.readUnsignedShort();
int uvID1 = is.readUnsignedShort();
int uvID2 = is.readUnsignedShort();
this.fTEXTURE[idx2+0] = (float)(this.fTexCoords[uvID0][0] / (float)this.pHeader.skinwidth); //s
this.fTEXTURE[idx2+1] = (float)(this.fTexCoords[uvID0][1] / (float)this.pHeader.skinheight); //t
this.fTEXTURE[idx2+2] = (float)(this.fTexCoords[uvID1][0] / (float)this.pHeader.skinwidth); //s
this.fTEXTURE[idx2+3] = (float)(this.fTexCoords[uvID1][1] / (float)this.pHeader.skinheight); //t
this.fTEXTURE[idx2+4] = (float)(this.fTexCoords[uvID2][0] / (float)this.pHeader.skinwidth); //s
this.fTEXTURE[idx2+5] = (float)(this.fTexCoords[uvID2][1] / (float)this.pHeader.skinheight); //t
idx += 3;
idx2 += 6;
}
Converting everything into buffers and drawing it:
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, this.TextureBuffer);
gl.glNormalPointer(GL10.GL_FLOAT, 0, this.NormalBuffer);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, this.VertexBuffer);
gl.glDrawElements(GL10.GL_TRIANGLES, (this.max_indices*3), GL10.GL_UNSIGNED_SHORT, this.IndexBuffer);
This is the result ( model is rendering fine with animations etc. but colors/texture is messed up - it should just color the feet )
How it should look( blender ): http://img6.imagebanana.com/img/rh6l4awq/blender.png and how it actually looks on my phone: http://img6.imagebanana.com/img/wud654s9/SC20120806172956.png
I saved the blender texture file as png ( View -> Pack as PNG -> save as )
Thanks for any help