How to distort an array of images - Processing - image-processing

I am trying to distort a grid of images that are displayed randomly when the mouse is clicked.
I have the grid and the random when click.
I have accomplished the distorsion I want when I have only one image.
Now I have to merge both codes together, but I can't figure out how to do it when the PImage is an array.
Grid code:
PImage img[];
int nPics;
int w, h;
void loadImages(){
for (int i = 0; i < nPics; i++) {
img[i] = loadImage("img_"+ nf(int(random(0, 687)), 3) + ".jpg");
imageMode(CORNERS);
}
}
void setup() {
size(1500, 500);
nPics=27;
img = new PImage[nPics];
w=width/9;
h=height/3;
loadImages();
}
void mousePressed(){
loadImages();
}
void draw() {
background(0);
for (int i=0; i<nPics; i=i+3) {
int col = i/3;
for (int row=0; row<3; row++)
image(img[i+row], col*w, row*h, (col+1)*w, (row+1)*h);
}
}
Wave code:
PImage myImage;
float speed1 = .01;
float speed2 = 5;
void setup()
{
size(1500,500);
myImage = loadImage("img_001.jpg");
}
void draw()
{
float distortion = map(mouseY, 0,500, 0, 10);
for (int i = 0; i < myImage.width; ++i) {
copy(myImage, i,0,1,height, i, (int) (sin((millis()+i*speed2)*speed1)*distortion),1,height);
}
}

If you want to apply the distortion to the entire canvas, you can just use copy() without the image parameter. This causes it to just copy from what is currently on the canvas.
You can use a very similar for loop to the one that's in your wave code, just omit the myImage parameter and let i go from 0 to width instead of myImage.width. Then you put it at the end of your draw block in the grid code:
//global variables, include speed1 and speed2
void loadImages() {
//as in grid code
}
void setup() {
//as in grid code...
}
void draw() {
//everything from grid code...
float distortion = map(mouseY, 0,500, 0, 10);
for (int i = 0; i < width; ++i) {
copy(i,0,1,height, //the rest...);
}
}

Related

Dart StageXL sprite color change on mouse click

I am relatively new to both StageXL and Dart and I am having difficulty changing the color of a Sprite on a mouse click. Currently I am just referencing the sprite and calling the graphics fillColor() method however nothing changes. Any ideas on how to change individual Sprite lines by mouse click?
class GameBoard
{
Stage stage;
int xPos;
int yPos;
var circle;
var line;
GameBoard(Stage s)
{
this.stage = s;
this.xPos = 100;
this.yPos = 100;
this.circle = new Sprite();
this.line = new Sprite();
}
Sprite generateDots(int x, int y, int size)
{
circle.graphics.circle(x,y,size);
circle.graphics.fillColor(Color.Black);
circle.addEventListener(MouseEvent.CLICK, reactCircle);
return circle;
}
Sprite generateHorzLines(int x, int y)
{
line.graphics.beginPath();
line.graphics.moveTo(x, y);
line.graphics.lineTo(x+100, y);
line.graphics.closePath();
line.graphics.strokeColor(Color.Gray);
line.addEventListener(MouseEvent.CLICK, reactHorzLine);
return line;
}
Sprite generateVertLines(int x, int y)
{
line.graphics.beginPath();
line.graphics.moveTo(x, y);
line.graphics.lineTo(x, y+100);
// this.line.graphics.closePath();
line.graphics.strokeColor(Color.Gray);
line.addEventListener(MouseEvent.CLICK, reactVertLine);
return line;
}
void generateBoard()
{
for(int i = 0; i < 5;i++)
{
for(int j = 0; j< 5;j++)
{
//render horizontal lines
if(j < 4)
{
stage.addChild(generateHorzLines(xPos,yPos));
}
//render vertical lines
if(i<4)
{
stage.addChild(generateVertLines(xPos,yPos));
}
//render points
stage.addChild(generateDots(xPos,yPos,5));
xPos+=100;
}
yPos+=100;
xPos = 100;
}
}
void reactHorzLine(MouseEvent event)
{
line.graphics.fillColor(Color.Red);
}
void reactVertLine(MouseEvent event)
{
line.graphics.fillColor(Color.Green);
}
void reactCircle(MouseEvent event)
{
circle.graphics.fillColor(Color.Blue);
}
}
The current version of StageXL (0.12) has no support for vector graphics when using the WebGL renderer only the Canvas2D renderer is supported. This will change with the next versions where vector graphics are also supported with the WebGL renderer. In the meantime you can opt-out of the WebGL renderer to use the Canvas2D renderer.
// do this before you construct the Stage
StageXL.stageOptions.renderEngine = RenderEngine.Canvas2D;
Btw. you will get best performance by using Bitmaps/BitmapDatas in StageXL. They are based on textures which will be rendered much faster than vector graphics.

EmguCV and Unity3D Interoperation

I managed integrating EmguCV into Unity3D and wrote a little converter that has some little problems
Step 1 Converting Unity3D Texture to OpenCV Image
public static Image<Bgr, byte> UnityTextureToOpenCVImage(Texture2D tex){
return UnityTextureToOpenCVImage(tex.GetPixels32 (), tex.width, tex.height);
}
public static Image<Bgr, byte> UnityTextureToOpenCVImage(Color32[] data, int width, int height){
byte[,,] imageData = new byte[width, height, 3];
int index = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
imageData[x,y,0] = data[index].b;
imageData[x,y,1] = data[index].g;
imageData[x,y,2] = data[index].r;
index++;
}
}
Image<Bgr, byte> image = new Image<Bgr, byte>(imageData);
return image;
}
Step 2 Converting OpenCV Image back to Unity3D Texture
public static Texture2D OpenCVImageToUnityTexture(Image<Bgr, byte> openCVImage, GameObject check){
return OpenCVImageToUnityTexture(openCVImage.Data, openCVImage.Width, openCVImage.Height, check);
}
public static Texture2D OpenCVImageToUnityTexture(byte[,,] data, int width, int height, GameObject check){
Color32 [] imageData = new Color32[width*height];
int index = 0;
byte alpha = 255;
for (int y = 0; y < width; y++) {
for (int x = 0; x < height; x++) {
imageData[index] = new Color32((data[x,y,2]),
(data[x,y,1]),
(data[x,y,0]),
alpha);
check.SetActive(true);
index++;
}
}
Texture2D toReturn = new Texture2D(width, height, TextureFormat.RGBA32, false);
toReturn.SetPixels32(imageData);
toReturn.Apply ();
toReturn.wrapMode = TextureWrapMode.Clamp;
return toReturn;
}
Compiler throws no errors but some goes wrong all the time. See yourself: cats.
On the left side is the original image, on the right side is the converted one. As you can see there are more cats then it should be...
Has anyone any clues?
Also it is slow as hell because of iterating twice through all pixels. Is there any better solution?
EDIT
This is the code where i draw my GUITextures:
public GameObject catGO;
GUITexture guitex;
Texture catTex;
void Start () {
guitex = GetComponent<GUITexture> ();
catTex = catGO.GetComponent<GUITexture> ().texture;
Image<Bgr, byte> cvImage = EmguCVUnityInterop.UnityTextureToOpenCVImage((Texture2D)catTex);
Texture2D converted = EmguCVUnityInterop.OpenCVImageToUnityTexture(cvImage);
guitex.texture = converted;
}
First of all you wrote in 2 for loops check.SetActive(true) so its width*height times. Enabling GameObject is a costly operation.
Second is that iterating thru every pixel is another costly operation. For examle if u have image 2560x1600 you have over 4 milion iterations.
Try to change TextureWrapMode to Repeat (I know it sounds silly:] )

XNA 4.0 3D Collision

I've been trying to work on a 3d forward-runner game (like temple run) in XNA 4.0.
I'm hitting a bit of a brick wall, so any help would be much appreciated!
Currently, I'm using my own method for collision detection, which requires the dimensions for each model to be hard-coded into the collision method. I've tried using the code from Microsoft, directly below, but it always returns false:
static bool CheckForCollisions(Entity c1, Entity c2)
{
for (int i = 0; i < c1.body.Meshes.Count; i++)
{
// Check whether the bounding boxes of the two cubes intersect.
BoundingSphere c1BoundingSphere = c1.body.Meshes[i].BoundingSphere;
c1BoundingSphere.Center += c1.position;
for (int j = 0; j < c2.body.Meshes.Count; j++)
{
BoundingSphere c2BoundingSphere = c2.body.Meshes[j].BoundingSphere;
c2BoundingSphere.Center += c2.position;
if (c1BoundingSphere.Intersects(c2BoundingSphere))
{
return true;
}
}
}
return false;
}
This was taken and modified very slightly from, Here My Entity class goes as follows.
Code of mine which I think is relevant would be:
public class Entity
{
public int rowID;
public Model body;
public Vector3 position;
public float rotation = 0f;
public float rotatePerFrame = 0f;
protected internal float toRight = 0;
protected internal float toLeft = 0;
protected internal float forward = 0;
protected internal float back = 0;
protected internal float bottom = 0;
protected internal float top = 0;
public void setDimensions(float right, float left, float front, float back, float top, float bottom)
{
this.toRight = right;
this.toLeft = left;
this.forward = front;
this.back = back;
this.top = top;
this.bottom = bottom;
}
public Entity RotateEnt(Entity e,float degrees)//Psuedo-only accurate to 90 degrees.
{
float actual = MathHelper.ToDegrees(degrees);
switch ((int)actual)
{
case 0:
break;
case 90:
// float temp = e.forward;
// e.forward = e.toLeft;
// e.toLeft =e.back ;
// e.back = e.toRight;
// e.toRight = temp;
float temp = e.forward;
e.forward = e.toRight;
e.toRight = e.back;
e.back = e.toLeft;
e.toLeft = temp;
break;
case 180:
e.forward = e.back;
e.back = e.forward;
e.toRight = e.toLeft;
e.toLeft = e.toRight;
break;
default: //case: 270
e.toRight = e.forward;
e.back = e.toRight;
e.toLeft = e.back;
e.forward = e.toLeft;
break;
}
return e;
}
public bool Collides(Entity e)
{
Entity c1 = RotateEnt(this, this.rotation);
Entity c2 = RotateEnt(e, e.rotation);
float myRightest = c1.position.X + c1.toRight;
float myLeftest = c1.position.X - c1.toLeft;
float hisRightest = c2.position.X + c2.toRight;
float hisLeftest = c2.position.X - c2.toLeft;
if(Collides1D(myLeftest, myRightest, hisLeftest, hisRightest))
{
float myTop = c1.position.Y + c1.top;
float myBottom = c1.position.Y - c1.bottom;
float hisTop = c2.position.Y + c2.top;
float hisBottom = c2.position.Y - c2.bottom;
if (Collides1D(myBottom, myTop, hisBottom, hisTop))
{
float myBack = c1.position.Z - c1.forward;
float myForward = c1.position.Z + c1.back;
float hisBack = c2.position.Z - c2.forward;
float hisForward = c2.position.Z + c2.back;
if (Collides1D(myBack, myForward, hisBack, hisForward))
{
return true;
}
}
}
return false;
}
}
static bool Collides1D(float left1, float right1, float left2, float right2)
{
if (left1 >= left2 && left1 <= right2)
return true;
if (right1 >= left2 && right1 <= right2)
return true;
if (left2 >= left1 && left2 <= right1)
return true;
if (right2 >= left1 && right2 <= right1)
return true;
return false;
}
My own method has been screwing up also, when trying to rotate models.
Ideally, it would be good to know what is wrong with the code from Microsoft, so that I can use it wherever, without worrying about hard-coding in object dimensions.
If anyone can see a fast fix to my own basic collision detection method, that would also be great.
I've looked at the Reimers tutorials, but I'm not getting them at the moment, maybe I've been staring at my own code for too long...
Any other information you want, I can try and supply. I can upload the models also, if that's the problem. I'm using models from Maya, exported as FBX.
I'm using MSVS 2010.
Thanks very much!
Jack
I think the problem may not be in the collision code, but in how you are updating the position of your Entitys. I don't see any update code or MoveForward(), etc, type of code. First of all, though, I think it would be much easier for you to use a Matrix instead of a bunch of float values for rotation. For example, you could have:
public class Entity
{
...
public Matrix RotationMatrix = Matrix.Identity;
public Vector3 position;
Public Entity(Vector3 FaceDirection, Vector3 UpDirection, Vector3 Position)
{
...
position = Position
RotationMatrix = Matrix.CreateWorld(Position, FaceDirection, UpDirection)
}
}
Then if you want to rotate, all you have to do is:
public Void RotateEnt(float Degrees)
{
RotationMatrix *= Matrix.CreateFromAxisAngle(RotationMatrix.Up, MathHelper.ToRadians(Degrees));
}
And if you do all this, then you should easily be able to update your Entity's position, which I think is the problem
public Void Update(GameTime gametime)
{
position += RotationMatrix.Forward * gametime.ElapsedRealTime.TotalMilliseconds * x; //x = some number to scale up or down velocity.
}
If you do this, I think your Entity's position will be updated, which then should fix your collision problem. But, not knowing how you update the position of your Entities, I am just speculating. HTH

aparapi start index of getGlobalId()

i use aparapi for parallelize and i wante to convert this java code:
public static void main(String[] args) {
float res = 0;
for (int i = 2; i < 5; i++) {
for (int j = 3; j < 5; j++) {
res += i * j;
}
}
System.out.println(res);
}
to its equivalent in aparapi:
Kernel kernel = new Kernel() {
#Override
public void run() {
int i = getGlobalId();
...
}
};
kernel.execute();
kernel.dispose();
There are a few issues here.
First your code is not data parallel. You have a 'race' condition on 'res' so this code cannot be computed on the GPU.
Secondly the range of execution is way too small. You are trying to execute 6 threads (x [2,3,4] * y [ 3,4]). This will not really gain any benefit from the GPU.
To answer the question regarding how you might implement over the 2 dim grid above.
Range range = Range.create2D(3, 2) ; // A two dimension grid 3x2
Kernel kernel = new Kernel() {
#Override
public void run() {
int x = getGlobalId(0)+2; // x starts at 2
int y = getGlobalId(1)+3; // y starts at 3
...
}
};
kernel.execute(range);
kernel.dispose();

How to develop custom List Field in Blackberry

In my app i have to show list of items in list field when i click on specific item in the list field the background color for a particular row change to grey color.How to develop this type of custom list field in Blackberrry.Any one please give ideas.
Thank You
you should draw rectangle in listfield row which is selected.. some thing like this. Here i have done it for on focus..
public void drawListRow(ListField list, Graphics g, int index, int y,int w) {
if (g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS))
{
g.setBackgroundColor(0x00572000);
//g.setBackgroundColor();
g.clear();
//g.setColor(Color.BLACK);
// g.fillRect(0,list.getWidth(),list.getWidth(),80);
g.setColor(Color.ORANGE);
g.fillRect(94,y+0,400,30);
//g.setColor(0x000000);
g.setColor(Color.WHITE);
g.drawText(text, 95, y+10, (DrawStyle.LEFT ), w );
}
else
{
g.setColor(0x00906966);
g.fillRect(94,y+0,400,30);
g.setColor(Color.ORANGE);
g.drawText(text, 95, y+10, (DrawStyle.LEFT ), w );
}}
Try this ...
private class MyListField extends ListField{
//0,ListField.MULTI_SELECT
private boolean hasFocus = false;
public void onFocus(int direction){
hasFocus = true;
}
public void onUnfocus()
{
hasFocus = false;
super.onUnfocus();
invalidate();
}
public void paint(Graphics graphics)
{ int width = Display.getWidth();
//Get the current clipping region
XYRect redrawRect = graphics.getClippingRect();
if(redrawRect.y < 0)
{
throw new IllegalStateException("Error with clipping rect.");
}
//Determine the start location of the clipping region and end.
int rowHeight = getRowHeight();
int curSelected;
//If the ListeField has focus determine the selected row.
if (hasFocus)
{
curSelected = getSelectedIndex();
}
else
{
curSelected = -1;
}
int startLine = redrawRect.y / rowHeight;
int endLine = (redrawRect.y + redrawRect.height - 1) / rowHeight;
endLine = Math.min(endLine, getSize() - 1);
int y = startLine * rowHeight;
//Setup the data used for drawing.
int[] yInds = new int[]{y, y, y + rowHeight, y + rowHeight};
int[] xInds = new int[]{0, width, width, 0};
//Set the callback - assuming String values.
ListFieldCallback callBack = this.getCallback();
//Draw each row
for(; startLine <= endLine; ++startLine)
{
//If the line we're drawing is the currentlySelected line then draw the fill path in LIGHTYELLOW and the
//font text in Black.
if(startLine == curSelected){
graphics.setColor(Color.LIGHTYELLOW);
graphics.drawFilledPath(xInds, yInds, null, null);
graphics.setColor(Color.BLACK);
graphics.drawText((String)callBack.get(this, startLine), 0, yInds[0]);
}
else{
//Draw the odd or selected rows.
graphics.setColor(Color.LIGHTGREY);
graphics.drawText((String)callBack.get(this, startLine), 0, yInds[0]);
}
//Assign new values to the y axis moving one row down.
y += rowHeight;
yInds[0] = y;
yInds[1] = yInds[0];
yInds[2] = y + rowHeight;
yInds[3] = yInds[2];
}
//super.paint(graphics);
}
}
.
.
.
refer this [LINK] : http://berrytutorials.blogspot.com/2009/11/create-custom-listfield-change.html

Resources