Android importing images to array [duplicate] - java

This question already has an answer here:
How to load BufferedImage in android?
(1 answer)
Closed 7 years ago.
I'm trying to load images to an array and can't figure out the syntax. I'm used to something like this in C#:
picture.Image = Image.FromFile(fileLocation);
That doesn't work here. Can anyone help me with this syntax, and any applicable imports I need to make. This is what I have:
public class Beards extends ActionBarActivity
{
Image [] beard = new Image[20];
String [] beardLocation = new String [20];
public void fillArrays()
{
for (int i = 0; i < 20; i++)
{
beardLocation[i] = "C:/Users/geoffoverfield01/AndroidStudioProjects/TheBeadery2.0/Images/Beards/pic_" + i + ".jpg";
}
for (int x =0;x<20;x++)
{
beard[x] = ImageIO.read(new File(beardLocation[x])); }
}
...
}
The library that allows me to use the ImageIO won't load.

I had to load some images for my Android project. This codes reads images and puts them into an Array.
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
bitmaps.add(BitmapFactory.decodeResource(this.getResources(), R.raw.one));
bitmaps.add(BitmapFactory.decodeResource(this.getResources(), R.raw.two));
bitmaps.add(BitmapFactory.decodeResource(this.getResources(), R.raw.three));
bitmaps.add(BitmapFactory.decodeResource(this.getResources(), R.raw.four));
Image is sitting on /res/raw/
my images are named one.jpg two.jpg three.jpg four.jpg
Thanks.

Related

JavaCV: convert array of integer to Mat

I am trying to implement face recognition in my photo database using JavaCV. While detecting possible faces works fine (there are a lot of examples for Java already), I am stuck at doing the actual recognition. To be more precise, at training the face recognizer.
For testing purposes I have a folder structure with a subfolder per known person labeled "s" + id, in which the training photos are located. What works is reading the images and adding them to an array. What does not work is creating a second array with the identifiers. LBPHFaceRecognizer.train does require a Mat and I cannot figure out how to create the required data structure. What I have so far is:
MatVector images = new MatVector();
List<Integer> ids = new ArrayList<Integer>();
File root = new File("orl_faces/");
for (File subFolder : root.listFiles()) {
if (subFolder.getName().matches("s\\d+") && subFolder.isDirectory()) {
int personId = Integer.parseInt(subFolder.getName().substring(1));
for (File file : subFolder.listFiles()) {
if (file.getName().endsWith(".pgm") && !"10.pgm".equals(file.getName())) {
IplImage img = cvLoadImage(file.getAbsolutePath());
images.put(img);
ids.add(personId);
}
}
}
}
// ---- FIXME here is where I am stuck ----
Mat labels = new Mat(new Size(ids.size(), 1));
for (int i = 0; i < ids.size(); i++) {
MatExpr m = Mat.ones(new Size(1, 1), CV_32SC1);
Mat m2 = m.asMat();
labels.push_back(m2);
}
model.train(images, labels);
When executing this, I get a
Exception in thread "main" java.lang.RuntimeException: vector<T> too long
at org.bytedeco.javacpp.opencv_face$FaceRecognizer.train(Native Method)
and obviously even if it did work, I still would not have my numbers in there. Any help is greatly appreciated.
You can use MatOfInt and an array of ints. For example, if you collect labels in List<Integer:
int[] allLabels = new int[labels.size()];
for (int i = 0; i < labels.size(); i++) {
allLabels[i] = labels.get(i);
}
faceRecognizer.train(faces, new MatOfInt(allLabels));
This should work :)

How to save a file to a certain folder which was downloaded in a rest URL request? [duplicate]

This question already has answers here:
How can I download and save a file from the Internet using Java?
(23 answers)
Closed 7 years ago.
I am using Yahoo's URL request ability to download stock data. I have found a java application that downloads the data every 5 seconds. I cant figure out how one would go about downloading stock data to a certain folder in ones computer while using the basic code I have used in the application. There has been other posts about how to save yahoo URL request data to a certain location but it does not use the same code format that I'm using. All ideas, source code, and links explaining how I should do this would be very helpful. Thank you for your help!
My code:
import java.awt.Desktop;
import java.net.URL;
public class Downloader {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
Thread.sleep(5000);
try {
Desktop.getDesktop()
.browse(new URL(
"http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=nab")
.toURI());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
you could use Java's IO capabilities, Are you trying to write a GUI, if not any specific reason to use AWT's Desktop class?
Try this sample code:
URL yahooFinance = new URL("http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=nab");
ReadableByteChannel channel = Channels.newChannel(yahooFinance.openStream());
FileOutputStream fos = new FileOutputStream("quotes.csv");
fos.getChannel().transferFrom(channel, 0, Long.MAX_VALUE);
You can also use org.apache.commons.io.FileUtils
java.net.URL yahooFinance = new java.net.URL("http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=nab");
File f = new File("quotes.csv");
FileUtils.copyURLToFile(yahooFinance, f);

read .pptx causes java.lang.ClassNotFoundException

In this question someone had a similar problem I have: I want to read the content of a .pptx file (only the text), but only got it work with .ppt files. So I tried to solve it with the accepted answer, but I got this exception: java.lang.ClassNotFoundException: org.apache.poi.hslf.model.TextPainter$Key
I used the example from this page (which was suggested in the accepted answer) so I have no idea why it does not work. My code:
public static String readPPTX(String path) throws FileNotFoundException, IOException{
XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(path));
String content = "";
XSLFSlide[] slides = ppt.getSlides();
for (XSLFSlide slide : slides){
XSLFShape[] sh = slide.getShapes();
for (int j = 0; j < sh.length; j++){
if (sh[j] instanceof XSLFTextShape){
XSLFTextShape shape = (XSLFTextShape)sh[j];
content += shape.getText() + "\n";
}
}
}
return content;
}
Solution to this issue is to add the poi-scratchpad-3.9.jar file to the classpath of the project.

Problems with scanning

I'm studying Biomedical Informatics and I'm now doing my clinical practice, where I have to check that the charges made to hospitalized patients were performed correctly on supplies that are of unique charging (every procedure and supplies used have a codification).
I can import the Excel file on the software I'm doing but, I don't know now how to do the scan.
Here is the code (I'm doing it on NetBeans),
public class Portal extends javax.swing.JFrame {
private DefaultTableModel model;
public static int con = 0;
public ArrayList listas = new ArrayList();
public ArrayList listasr = new ArrayList();
public Portal() {
initComponents();
model = new DefaultTableModel();
jTable1.setModel(model);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser examinar = new JFileChooser();
examinar.setFileFilter(new FileNameExtensionFilter("Archivos Excel", "xls", "xlsx"));
int opcion = examinar.showOpenDialog(this);
File archivoExcel = null;
if(opcion == JFileChooser.APPROVE_OPTION){
archivoExcel = examinar.getSelectedFile().getAbsoluteFile();
try{
Workbook leerExcel = Workbook.getWorkbook(archivoExcel);
for (int hoja=0; hoja<leerExcel.getNumberOfSheets(); hoja++)
{
Sheet hojaP = leerExcel.getSheet(hoja);
int columnas = hojaP.getColumns();
int filas = hojaP.getRows();
Object data[]= new Object[columnas];
for (int fila=0; fila < filas; fila++)
{
for(int columna=0; columna < columnas; columna++)
{
if(fila==0)
{
model.addColumn(hojaP.getCell(columna, fila).getContents());
}
System.out.println(hojaP.getCell(columna, fila).getContents());
if(fila>=1)
data[columna] = hojaP.getCell(columna, fila).getContents();
}model.addRow(data);
}
}
model.removeRow(0);
JOptionPane.showMessageDialog(null, "Excel cargado exitosamente");
}
}
}
Before you import the excel file save it as a csv(comma delimited) file(remeber to delete the headings). Then open the netbeans project folder under my documents, then open the your project folder and dump the csv file in their. Look at your project under files in netbeans open the folder and you will see the file in their. Now you said you want to read the file/ scan the file.
You can use my method at first, understand it and adapt to other scenarios you have in the future.
First create a class or use an readily created( you already created java class).
Declare arrays depending on how many rows you had in the excel file not the csv file and a counter.
Example two.
String [] patientsnamess;
int [] ages;
int count;
Now initiate the arrays in a deafault constructor(you don't have to because you can do it when you declare them but it is conventional). You can learn about constructors there are two I know of or there are only two but I will only show a default constructor.
It will look like this.
public yourClassName(){
patientsnames = new String[400];//the number in square brackets are an example it sets the size of the array. You can set the size according to how many patients there are or you could just use lists as the limit on the list as dependent on primary and virtual memory.
ages = new int[400];
count = 0;
}
now create the method two read the text file.
public void readFile(){
count = 0;//important
Scanner contents = null;
try{
contents = new Scanner(new FileReader("You file's name.txt");
while(contents.hasNext()){
String a = contents.nextLine();
String p[]= a.split("\\;");
patientsnames[count] = p[0];
ages[count] = p[1];
count++;//important
}
}
catch(FileNotFoundException e){
System.out.println(e.getMessage());
}
}
Now create get methods to call up the arrays with the values from the file.(Find out on rest of stackoverflow).
Remeber that field types link up with the data in the file.
I really hope this works for you. If not I am sorry but good luck with your Biochemical Informatics course.
Remeber to call the readFile method with an object in this case or it won't work.
Research the neccessary imports such as:
import java.io.*;
import java.util.*;

JAppet loading images

I made a game using JFrame, and now I want to deploy it in JApplet, yet I get the following exception:
java.lang.ExceptionInInitializerError
As much as Google told me it is caused by static initializers, and the only thing I do in my static initialization blocks is call to the following function:
public static BufferedImage[] loadAnimation (String fileName, int subimagewidth, int subimageheight, int pixelsbetweensprites) {
BufferedImage spr = null;
BufferedImage[] animation;
int x, y; //amount of images in each direction
try {
Object ob = new Object();
spr = ImageIO.read(ob.getClass().getResourceAsStream(fileName));
} catch (IOException ex) {
System.exit(0);
Logger.getLogger(AnimationLoader.class.getName()).log(Level.SEVERE, null, ex);
}
x = spr.getWidth() / subimagewidth;
y = spr.getHeight() / subimageheight;
animation = new BufferedImage[x*y];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
animation[j*x+i] = spr.getSubimage(i*(subimagewidth + pixelsbetweensprites), j*(subimageheight+pixelsbetweensprites), subimagewidth, subimageheight);
}
}
return animation;
}
Is this problem occurs because it is JApplet, or because it is unsigned?
How to fix it (preferably without spending money on signature)?
This:
Object ob = new Object();
spr = ImageIO.read(ob.getClass().getResourceAsStream(fileName));
You probably want to load the image from the same location your code originates from (e.g. a jar file). Instead you ask java.lang.Object.class to give back the stream of the image which is probably not you want (this would search the filename resource in the internal libraries of the JRE or JDK - more specifically in the rt.jar file).
If indeed you want to load the image from the same jar your class files originates from, you should acquire the stream like this:
InputStream in = YourClass.class.getResourceAsStream(filename);
You should pass this InputStream to your loadAnimation() method, or pass both the Class along with the file name to be used to get the stream of the image.

Categories