How to find out detected face is real or fake - java

I am developing one security related project, there is need to check any face is detected or not, if face is detected then do some action, if face is not detected then close app.
Everything is perfect working, i am using SurfaceView which is implemented SurfaceHolder.Callback and in that open camera and camera have one method name is startFaceDetection using this method i detect face.
code for reference
public class SurfaceViewPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public SurfaceViewPreview(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
if (Camera.getNumberOfCameras() <= 0 || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
return;
mCamera = Camera.open(0);
mCamera.setPreviewDisplay(mHolder);
} catch (Exception e) {
e.printStackTrace();
if (this.mCamera != null) {
this.mCamera.release();
this.mCamera = null;
}
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (Camera.getNumberOfCameras() <= 0 || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
return;
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (Camera.getNumberOfCameras() <= 0 || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
return;
mCamera.startPreview();
mCamera.setFaceDetectionListener(new Camera.FaceDetectionListener() {
#Override
public void onFaceDetection(Camera.Face[] faces, Camera camera) {
// face is detected.
}
});
mCamera.startFaceDetection();
}
}
Now, problem if any human post if i shown to camera then detected as human, but i want real human face detection not fake poster face.
Possible way to handle my requirement.
1) Capture 10 images periodically and check all variation is same then it means static face is there (like poster which is mounted in wall).
2) Write any proper algorithm which tell to detected face is real human or fake face.
3) Any library is available which is said human face is really available or not.
if anyone have idea please suggest, how to solve above issue (any code is available then share with me), response is appreciated !
how can use adapting learning ways to conclude real vs fake picture/video frame.

You could use the parallax effect. First you take a 2 pictures from 2 different locations which are like 2cm apart. then you could compare the images and see:
*If they are very similar(almost same) then the image is 2d and it is a poster
*If they are very different then it is a 3d Face
Another way you could do this is by using the camera flash. The flash would cause a bit of reflection on photographs and this would prevent people from using a video to bypass your system as a screen would cause a lot of glare would would block the face preventing the camera from detecting the face. All you would need to do is add a flash(preferably blinking at like 100Hz so the people can't see it but it would show up in a picture)
I hope this helped :)

I had a challenge solving problems similiar the one #YogeshRathi. I had an algorithm with the CV2 library (Python) recognizing faces taken from a security camera.
Every 5 seconds I took pictures, and the algorithm recognized faces in the poster hanged on the wall.
After test different solutions (other algorithms, train models...) what I did finally was generate a buffer, in which there were 5 pictures always, one in and another out. The one entering to the buffer do it with the list of coordinates of all rectangles that contains a face (5 faces in the pictures --> 5 rectangles), and compare with the rest of the pictures inside the buffer.
The comparison of pictures consists in compare the rectangles (every rectangle has 4 coordinates) between both pictures, by the substraction of every single coordinate. If the rectangle is static (a face in a poster have almost the same rectangle in different pictures) the difference between both rectangles is simbolic, so then, unless they have different number of rectangles, if all the rectangles in both pictures have simbolic differences they are similar.
If in a picture appears a real person we will have different number of rectangles (the number of faces inside the poster and the one that belongs to the real person), o at least one of them will be different to the list of rectangles of the picture is being compared with.
If the rectangles in both pictures are similar, I put a flag in a Historial field, that is 0. If there are different rectangles, the flag is 1.
You compare the picture that enters the buffer one to one to the rest of the pictures in the buffer. So when you finish, you have a list of flags (like this [0,0,0,1,1]) attached to every picture.
When the picture go out of the buffer you evaluate the Historial field. If a 0 is contained in the list it means that at least there are a picture that is identical, so then you can consider there are no faces on it you have to identify, because all it contains only fake faces from a poster.

Related

How to rotate images every tick?

GitHub
I’m making a gear simulator and I’ve set it up where you can place the gears, and I have a plan on how you can update each gears rotation speed. I’m going to make a Initialize (method?) where I make the gear that will spin check every point next to it(it’s beta size hasn’t been implemented yet) and then I will add the original gear to a dontSpin list, then make every gear the first one detected spin everything around it, except for gears in dontSpin.
My issue I’m having is how do I rotate the gear Image a bit every tick? I’ve done a bunch of research and tried implementing some things I found but they all rotate it once, and I can’t find a way/I’m not smart enough to know how to make each gear object in the gearList rotate at the rotateSpeed every tick.
If you need more information please message me as I’ve been working on this for like a week and this has been a roadblock for at least 3 days making me lose motivation.
I tried researching multiple different sites and different methods of rotating images and it seemed none were what I needed, they seemed to all be a single rotation. I tried just staring at my code for 15 minutes waiting for it to just pop in my head to no avail. I tried asking on a discord help server, where I was told “just make a method to rotate it, then use it” and I’m not even kidding lmao. I even tried asking a fellow java coder about it, but they had no idea.
Help me stack overflow, you’re my only hope.
Edit: taken down for focusing on 2 problems , so I’ll elaborate on the one problem.
Gear is a class with a Point(x,y), I have a Board class with the bulk of my code, where I have a 10 by 10 ish size grid of squares, the gear and player automatically moves around on these squares.
You can hit a button ‘E’ to add a gear, and ‘Q’ to remove a gear. Every time you add a gear, a new gear is added to the gearList ArrayList. My issue is how to update the gear Images every single tick in the board class.
Here is where the gears are drawn
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// when calling g.drawImage() we can use "this" for the ImageObserver
// because Component implements the ImageObserver interface, and JPanel
// extends from Component. So "this" Board instance, as a Component, can
// react to imageUpdate() events triggered by g.drawImage()
// draw our graphics.
drawBackground(g);
drawScore(g);
for (Gear gear : gearList) {
gear.draw(g, this);
}
player.draw(g, this);
// this smooths out animations on some systems
Toolkit.getDefaultToolkit().sync();
}
This is what that calls
public class Gear {
// image that represents the gear's position on the board
private BufferedImage image;
private BufferedImage newSizeImage;
// current position of the gear on the board grid
private Point pos;
private int rot = 45;
private int rotSpeed = 5;
public Gear(Point gpos) {
// load the assets
loadImage();
// initialize the state
pos = gpos;
}
private void loadImage() {
try {
// you can use just the filename if the image file is in your
// project folder, otherwise you need to provide the file path.
image = ImageIO.read(new File("src/images/gear.png"));
finalImage = rotate(image.getScaledInstance(Board.TILE_SIZE, Board.TILE_SIZE, Image.SCALE_DEFAULT));
} catch (IOException exc) {
System.out.println("Error opening image file: " + exc.getMessage());
}
}
public void draw(Graphics g, ImageObserver observer) {
// with the Point class, note that pos.getX() returns a double, but
// pos.x reliably returns an int. https://stackoverflow.com/a/30220114/4655368
// this is also where we translate board grid position into a canvas pixel
// position by multiplying by the tile size.
g.drawImage(
finalImage,
pos.x * Board.TILE_SIZE,
pos.y * Board.TILE_SIZE,
observer);
}

How to make Android views shape other than rectangular

I'm dealing with collision detection with some animated views and I'm animating some alpha image views. What's happening is that the collision detection is triggered even when the second object is on the transparent part of the ImageView when it's apparently not touching it but the ImageView container is rectangular box which exceeds the image bounds.
How can I detect when it touches the drawn part of the image or making the container a triangle?
Here's how Im detecting collision between two views:
public boolean checkCollision(View v1, View v2) {
if (v1 == null || v2 == null) {
log.e("Views must not be null");
throw new IllegalArgumentException("Views mut be not null");
}
Rect R1 = new Rect();
v1.getHitRect(R1);
Rect R2 = new Rect();
v2.getHitRect(R2);
return Rect.intersects(R1, R2);
}
What I would recommend doing is to do an initial check of the bounding boxes just to see if you need to perform a more accurate checking. This step is optional if you only have a few objects colliding, but if you have a lot of them it will save a lot of performance.
If you do need to do a further check, make points around the image where you know there is solid texture and then check for a collision with those points. I can try and get you some code for this if you would like, but check out this question here which explains things in depth.
https://gamedev.stackexchange.com/questions/30866/collision-detection-with-non-rectangular-images

Make bitmap shake like that

I have a bitmap of bird flying from point a straight to point b, and I want to make the movement a bit more natural, with some wiggles and small random movements that are smooth and not jittery, I'm using canvas so I can't use xml, but is there something automatic that can add some natural shakes to the bitmap while it is moving like animator?
Something like that:
My first idea was getting random points around the bitmap and moving it towards them, but that would look very robotic and not smooth, is there some calculation I can do to make the movement between points smoother?
I will also be happy to hear other ideas of creating a wiggle effect, any idea will help because I cant think of anything, nor find anything.
Here is the flying code:
public void fly(float x1,float y1,float scale){
flyTo.x=x1;
flyTo.y=y1;
this.scale=scale;
mCurrentState=BossState.Flying;
}
private void UpdateAll(){
switch (mCurrentState) {
case Flying:
if(flyTo.x==position.x&&flyTo.y==position.y){
mCurrentState=BossState.Normal;
}
else{
if(flyTo.x>position.x){
position.x+=speed;
}
else if(flyTo.x<position.x){
position.x-=speed;
}
if(flyTo.y>position.y){
position.y+=speed;
}
else if(flyTo.y<position.y){
position.y-=speed;
}
}
break;
...
}

OpenCV's FrameGrabber's Output Image is Incorrect

I am working on an OpenCV project that relies on finger detection. Currently I have an OpenCVFrameGrabber that grabs a frame and places it in an IplImage. I then draw that image onto my GUI.
This all works, but the image that is drawn seems to be in black and white even though I have a color camera. There are noticeable vertical lines in the image and when there is some color, it seems to be split into components along these lines.
Does anyone know of a way to get the original webcam image?
I recently started playing with JavaCV and I'm always trying to avoid this new classes and stick with the "original" OpenCV methods.
I suggest you try the following code and make sure that the most simple capture procedure works:
public static void main(String[] args)
{
CvCapture capture = cvCreateCameraCapture(0);
if (capture == null)
{
System.out.println("!!! Failed cvCreateCameraCapture");
return;
}
cvNamedWindow("camera_demo");
IplImage grabbed_image = null;
while (true)
{
grabbed_image = cvQueryFrame(capture);
if (grabbed_image == null)
{
System.out.println("!!! Failed cvQueryFrame");
break;
}
cvShowImage("camera_demo", grabbed_image);
int key = cvWaitKey(33);
if (key == 27)
{
break;
}
}
cvReleaseCapture(capture);
}
If this works, your problem might be related to OpenCVFrameGrabber. If it doesn't, you might want to experiment your code with another camera.

Android Missile sprite

I am trying to make a onTouchEvent to create a missile that will launch from my character sprite and forward.
I have this working using
if (missdraw = true){
canvas.drawBitmap(missile,missilex,missileY,null);
missilex = missilex + 14;
missdraw = false;
}
in my onDraw method, but the problem is it will only create one at a time.
I tried to create a class to deal with this, but this just causes an error and crashes when i try to fire.
here is what i use for the class: (this is in the ondraw in my gameview)
for (Batcher missile : missiles ){
missile.onDraw(canvas);
}
this is in the class
public Batcher(List<Batcher> temps, ScreenActivity newView, float x,
float y, Bitmap missile){
this.x = 1;
this.y = 2;
this.missile = missile;
}
public void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(missile, x,y, null);
}
I would appreciate any help, but also if you could explain how it would work, instead of just code, as im quite new to programming, and really need to understand what im doing and why im doing it, rather than just copying peoples code because it works.
Cheers Phil.
Your concepts are pretty good, actually. There are a few things I don't quite understand about the code samples you posted up, I'll try to translate into what I'd do and you can tell me if I'm doing it wrong :)
in your game class you need (and it looks like you have) a list of Missiles:
LinkedList<Batcher> missiles;
In your onTouch(), however a missile is created -
missiles.add(new Batcher(missilex, missiley, missile));
you now have a collection of missiles. Note that I didn't include the list in the constructor of your batcher, because an object should never need to know that it's a part of a collection. All it needs to know is how to draw itself and where. Since I assume that all of your missiles will be added to or removed from the screen frequently, while only having a few on screen at a time, I've used a LinkedList, which is fast for adding and removing, but slow for accessing a specific missile. If you needed to access specific items in the collection and the collection didn't change very much, you would use an ArrayList instead. on to onDraw - as you have it the missile draws itself, which is fine, but I prefer to let the View do the drawing, with the missile telling it where it should be drawn -
for (Batcher missile : missiles ){
missile.setX(missile.getX() + 14); // to make it move
if (missile.getX() > canvas.gedWidth()) { //check if it's left the screen
missiles.remove(missile); // Remove it
}
else { //perform drawing
canvas.drawBitmap(missile.getBitmap(), missile.getX(), missile.getY(), null);
}
}
Hopefully that'll do it for you, but feel free to let me know if there's anything you'd like me to explain more!

Categories