I am trying to implement a fuction that checks whether a png image contains a human face. I am trying to use OpenImaj and noticed that it has 4 detectors (Identity, Haar etc)
Appreciate if anyone can share a relevant code snippet
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.openimaj.image.DisplayUtilities;
import org.openimaj.image.FImage;
import org.openimaj.image.ImageUtilities;
import org.openimaj.image.MBFImage;
import org.openimaj.image.colour.RGBColour;
import org.openimaj.image.colour.Transforms;
import org.openimaj.image.processing.face.detection.DetectedFace;
import org.openimaj.image.processing.face.detection.FaceDetector;
import org.openimaj.image.processing.face.detection.HaarCascadeDetector;
import org.openimaj.math.geometry.shape.Rectangle;
public class App {
public static void main(String[] args) throws Exception, IOException {
final MBFImage image = ImageUtilities.readMBF(new File("d:\\java\\face\\bin.jpeg"));
FaceDetector<DetectedFace, FImage> fd = new HaarCascadeDetector(200);
List<DetectedFace> faces = fd.detectFaces(Transforms.calculateIntensity(image));
System.out.println("# Found faces, one per line.");
System.out.println("# <x>, <y>, <width>, <height>");
for (Iterator<DetectedFace> iterator = faces.iterator(); iterator.hasNext();) {
DetectedFace face = iterator.next();
Rectangle bounds = face.getBounds();
image.drawShape(face.getBounds(), RGBColour.RED);
// System.out.println(bounds.x + ";" + bounds.y + ";" + bounds.width + ";" +
// bounds.height);
}
DisplayUtilities.display(image);
}
}
Related
I am currently learning how to program minecraft mods using fabric. I want to create an Item, which, when used on a creeper, let the player explode, which will also be shown in the deathmessage, that the player was the cause of the death(like when you kill yourself with TNT).
package net.lurchfresser.tutorialmod.item.custom;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.mob.CreeperEntity;
import net.minecraft.entity.mob.ZombieEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.world.World;
import org.w3c.dom.Text;
public class ConsumerItem extends Item {
public ConsumerItem(Settings settings){
super(settings);
}
#Override
public ActionResult useOnEntity(ItemStack stack, PlayerEntity user, LivingEntity entity, Hand hand) {
double x = user.getX();
double y = user.getY();
double z = user.getZ();
if(!user.world.isClient) {
if (entity instanceof ZombieEntity) {
entity.kill();
user.addStatusEffect(new StatusEffectInstance(StatusEffect.byRawId(19), 100));
} else if (entity instanceof CreeperEntity) {
entity.kill();
user.world.createExplosion(user, null,null, x + 0.5D, y + 0.5d, z + 0.5d,3F,false,World.ExplosionSourceType.MOB);
}
}
return super.useOnEntity(stack, user, entity, hand);
}
}
If I put the creeper in the first param of the createExplosion method. The Creeper will be the cause of the death. Also trying pass user.getName.toString in the second param(damageSource) didn't work out.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.management.AttributeChangeNotification;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.RDFReaderI;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.system.StreamRDFWriter;
import org.apache.jena.vocabulary.VCARD;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.DataUtilities;
import org.geotools.data.FeatureSource;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.Query;
import org.geotools.data.ServiceInfo;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.opengis.feature.ComplexAttribute;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.FeatureType;
import org.opengis.filter.Filter;
public class ShpToRdf {
public static void main(String[] args) throws IOException {
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> values = new ArrayList<String>();
File file = JFileDataStoreChooser.showOpenFile("shp", null);
if (file == null) {
return;
}
FileDataStore myData = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource source = myData.getFeatureSource();
SimpleFeatureType schema = source.getSchema();
Query query = new Query(schema.getTypeName());
query.setMaxFeatures(100);
Model model = ModelFactory.createDefaultModel();
String shpURI = "http://www.shp.fake/";
Resource shapeFile = model.createResource(shpURI);
FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures(query);
try (FeatureIterator<SimpleFeature> features = collection.features()) {
while (features.hasNext()) {
SimpleFeature feature = features.next();
model.setNsPrefix("shp", shpURI);
for (org.opengis.feature.Property attribute : feature.getProperties()) {
names.add(attribute.getName().toString());
values.add(attribute.getValue().toString());
}
}
}
ArrayList<Integer> ids = new ArrayList<Integer>();
for(int i=0; i<names.size();i++) {
if (names.get(i).equals("Id")) {
ids.add(i);
}
}
Property features = model.createProperty(shpURI,"features");
for(int i = 0; i<ids.size();i++) {
Property id = model.createProperty(shpURI,names.get(ids.get(i)));
shapeFile = model.createResource(shpURI)
.addProperty(features, model.createResource()
.addProperty(id,model.createResource()
.addProperty(id, values.get(ids.get(i)))
.addProperty(features, "feature1")
.addProperty(features, "feature2")
.addProperty(features, "feature3")));
}
RDFDataMgr.write(System.out, model, Lang.RDFXML);
}
}
I am trying to create an application that converts Shape File(shp) to RDF.
The problem is that I can get two ArrayLists from the shp. The one has the names of the values (id,name,geometry etc.), and the other has the values.
To create the RDF, I have to match each Id with the matching values(ex. Id =1 has name = road 1, geometry = line etc.)
Could you help me with this?
Thank you!
I think you should be able to do this by tweaking the following bit of logic
for (org.opengis.feature.Property attribute : feature.getProperties()) {
names.add(attribute.getName().toString());
values.add(attribute.getValue().toString());
}
Instead of putting them in two lists, you can put them in a list of pairs. This way when you iterate over the list, you know the mapping between the subject and object.
It should look something similar to
List<Pair<String, Integer>> contentList = new ArrayList<Pair<String, String>>();
for (org.opengis.feature.Property attribute : feature.getProperties()) {
Pair<String, Integer> subjectObjectPairs = new Pair<String, String>(attribute.getName().toString(), attribute.getValue().toString());
contentList.add(subjectObjectPairs);
}
I'm not sure what the ids ArrayList is for, but you could move that logic into the for loop above to make sure you're only getting identifiers.
Okay, so I am attempting to make a custom spawners plugin, but I've already hit a bit issue.. I cannot figure out how to change what creature the spawner summons. The code I have currently can be found below (This is a SpawnerSpawnEvent, also everything works other than the spawning of the skeleton, The console gets sent the 'File exists' message, The file does indeed exist (This is done in the block place event, I will also include this below, not sure if it is needed.) so I am very confused on how I could achieve this..) Thank you in advance for your time.
SpawnerSpawnEvent »
package me.askingg.events;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.SpawnerSpawnEvent;
import me.askingg.golems.Main;
public class CreatureSpawn implements Listener {
Main plugin;
#EventHandler
public void coalSpawn(SpawnerSpawnEvent event) {
CreatureSpawner spawner = (CreatureSpawner) event.getSpawner().getBlock().getState();
Location location = spawner.getLocation();
String world = spawner.getWorld().getName().toString();
File locationFile = new File("plugins/Golems/Locations", world + " - " + location.getBlockX() + "-"
+ location.getBlockY() + "-" + location.getBlockZ() + ".yml");
if (locationFile.exists()) {
Bukkit.getConsoleSender().sendMessage(Main.colorCodes(Main.prefix + "&fThe file exists..."));
spawner.setSpawnedType(EntityType.SKELETON);
spawner.update();
}
}
}
BlockPlaceEvent »
package me.askingg.events;
import java.io.File;
import java.io.IOException;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import me.askingg.golems.Main;
public class BlockPlace implements Listener {
#EventHandler
public void spawnerPlace(BlockPlaceEvent event) {
Player player = (Player) event.getPlayer();
Block block = event.getBlock();
Location location = block.getLocation();
String world = block.getWorld().getName().toString();
if (block.getType().equals(Material.SPAWNER)) {
if (player.getInventory().getItemInMainHand().getItemMeta().getDisplayName()
.equals(Main.colorCodes("&fSkeleton Spawner"))) {
File locationFile = new File("plugins/Golems/Locations", world + " - " + location.getBlockX() + "-"
+ location.getBlockY() + "-" + location.getBlockZ() + ".yml");
if (!(locationFile.exists())) {
try {
locationFile.createNewFile();
Bukkit.getConsoleSender()
.sendMessage(Main.colorCodes(Main.prefix
+ "&aSuccessfully&f created a new &fSkeleton Spawner&f location &8(&a"
+ world + " &8-&a " + location.getBlockX() + "&8-&a" + location.getBlockY() + "&8-&a"
+ location.getBlockZ() + "&8)"));
} catch (IOException e) {
}
}
}
}
}
}
Alright, so. Based on my quick read of the documentation it looks like you can cast "block" in this instance to CreatureSpawner and then set the spawnType.
Example:
if (block.getType().equals(Material.SPAWNER)) {
CreatureSpawner spawner = (CreatureSpawner) block;
spawner.setSpawnType(EntityType.SKELETON);
}
Be aware some of that maybe pseudo code as I didn't delve that much into the Bukkit API documentation but you should be able to figure it out from there.
I am working on a project involving Hadoop and Mahout libraries. I have to use SequenceFile.Writer to write data to a file but I am getting a nullpointer exception when I am trying to use SequenceFile. To better understand my problem I have written a test code which is re-creating the problem and also the error message. I am also adding the code to generate the sample data.
Here first I am generating a sample data based on some distribution in the MyUtil class. Then passing the sample data to do canopy clustering(in the test Class) using Mahout's canopy clustering library. Then trying to write the centriods produced by the canopy clustering algorithm to a file using the SequenceFile.Writer. This is where I am getting the null pointer exception(When Creating the Sequence File Writer)
Thanks in advance for your help.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.Writer;
import org.apache.mahout.clustering.canopy.Canopy;
import org.apache.mahout.clustering.canopy.CanopyClusterer;
import org.apache.mahout.clustering.canopy.CanopyDriver;
import org.apache.mahout.common.distance.EuclideanDistanceMeasure;
import org.apache.mahout.math.Vector;
public class Test {
public static void main(String[] args) throws IOException{
List<Vector> sampleData = new ArrayList<Vector>();
MyUtil.generateSamples(sampleData, 400, 1, 1, 2);
MyUtil.generateSamples(sampleData, 400, 1, 0, .5);
MyUtil.generateSamples(sampleData, 400, 0, 2, .1);
#SuppressWarnings("deprecation")
List<Canopy> canopies = CanopyClusterer.createCanopies(sampleData,
new EuclideanDistanceMeasure(), 3.0, 1.5);
Configuration conf = new Configuration();
File testData = new File("testData/points");
if(!testData.exists()){
testData.mkdir();
}
Path path = new Path("testData/points/file1");
SequenceFile.Writer writer = SequenceFile.createWriter(conf,
SequenceFile.Writer.file(path),
SequenceFile.Writer.keyClass(LongWritable.class),
SequenceFile.Writer.valueClass(Text.class));
for(Canopy canopy: canopies){
System.out.println("Canopy ID: "+canopy.getId()+" centers "+
canopy.getCenter().toString());
writer.append(new LongWritable(canopy.getId()),
new Text(canopy.getCenter().toString()));
}
writer.close();
}
}
MyUtil.generateSamples is just generating the sample data(I have also added the code below). And the error message the above code is throwing is
Exception in thread "main" java.lang.NullPointerException
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1010)
at org.apache.hadoop.util.Shell.runCommand(Shell.java:445)
at org.apache.hadoop.util.Shell.run(Shell.java:418)
at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:650)
at org.apache.hadoop.util.Shell.execCommand(Shell.java:739)
at org.apache.hadoop.util.Shell.execCommand(Shell.java:722)
at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:633)
at org.apache.hadoop.fs.FilterFileSystem.setPermission(FilterFileSystem.java:467)
at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:456)
at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:424)
at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:906)
at org.apache.hadoop.io.SequenceFile$Writer.<init>(SequenceFile.java:1071)
at org.apache.hadoop.io.SequenceFile$RecordCompressWriter.<init>(SequenceFile.java:1371)
at org.apache.hadoop.io.SequenceFile.createWriter(SequenceFile.java:272)
at Test.main(Test.java:39)
To Generate the sample data
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.random.Normal;
public class MyUtil {
public static void generateSamples(List<Vector> vectors, int num,
double mx, double my, double sd){
Normal xDist = new Normal(mx, sd);
Normal yDist = new Normal(my, sd);
for(int i=0; i<num; i++){
vectors.add(new DenseVector(new double[]{xDist.sample(), yDist.sample()}));
}
}
}
}
I have a .doc file, I Want to find superscript and subscript using Apache-poi.
Following example shows a way to read superscript/subscript from a docx file. Doc will be similar too.
package demo.poi;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.VerticalAlign;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
public class DocReaderTest {
#Test
public void showReadDocWithSubscriptAndSuperScript() throws IOException, InvalidFormatException {
File docFile = new File("C:/temp/sample.docx");
XWPFDocument hdoc = new XWPFDocument(OPCPackage.openOrCreate(docFile));
Iterator<XWPFParagraph> paragraphsIterator = hdoc.getParagraphsIterator();
while (paragraphsIterator.hasNext()) {
XWPFParagraph next = paragraphsIterator.next();
for (XWPFRun xwrun : next.getRuns()) {
VerticalAlign subscript = xwrun.getSubscript();
String smalltext = xwrun.getText(0);
switch (subscript) {
case BASELINE:
System.out.println("smalltext, plain = " + smalltext);
break;
case SUBSCRIPT:
System.out.println("smalltext, subscript = " + smalltext);
break;
case SUPERSCRIPT:
System.out.println("smalltext, superscript = " + smalltext);
break;
}
}
}
}
}