Programmatically Load Texture in Image and Set Border to the Image Unity - image

I am developing a endless game, and want to take a Snapshot when the player Dies. I've almost done that using Texture2D. i have done Load Texture in image programmatically. but want to set border to the image. How can i do that.? how can i set border to that image at Run-time.?
This Code For Load Texture To the Image at Run-time when my player Dies.
void LoadImage(){
byte[] bytes = File.ReadAllBytes (Application.dataPath +"/GameOverScreenShot" + "/BirdDiedScreenShot.png");
Texture2D texture = new Texture2D (900, 900, TextureFormat.RGB24, false);
texture.filterMode = FilterMode.Trilinear;
texture.LoadImage (bytes);
Sprite sprite = Sprite.Create (texture, new Rect (0, 0, 700, 380), new Vector2 (0.5f, 0.0f), 1.0f);
imgObject.GetComponent<UnityEngine.UI.Image> ().sprite = sprite;
}
i want to Set Border to that image at Run-time. any one can help i really appreciate. thanks in Advance.

Do this after you load the image into the Texture2D variable and this will change the border of the image to whatever color you want.
//color should be a variable that holds the color of the border you want.
for (int i = 0; i< texture.width; i++){
texture.SetPixel(i, 0, color); //top border
texture.SetPixel(i, texture.height - 1, color); //bottom border
}
for (int j = 0; j < texture.height; j++){
texture.SetPixel(0, j, color); // left border
texture.SetPixel(texture.width - 1, j, color); //right border
}
texture.Apply();
This will replace any pixels on the edge of your original image so if you need those edge pixels you will need to look for another solution. Also, texture.Apply takes a while to run so if you need to constantly apply this border you may experience slowdown but you mentioned it is only when the player dies so this should not be an issue.

Related

PImage background color specified not working - SOLVED, see below

I am working my way through Ira Greenberg's original version of "Processing: Creative Coding and Computational Art." On page 195 there is an example of using the PImage class for draw lines using pixels. The code is fairly simple and does not even use the setup and draw functions. My problem is that I cannot get the sketch to work by making a white background and black lines. I have to change it to make a black background and white lines. Take note that the background call should make it white but turns out black. I cannot find a relevant example online. Here is the code with the changed code specified on lines 5, 9, and 10.
/* program: p195_lines_with_pixels.pde
This program shows how to create lines with pixels. This seems like it has been covered.
However, this program uses the PImage library. */
size(500, 300);
background(255); // not working as specified
// used by diagonal lines
float slope = float(height)/float(width);
PImage img = createImage(width, height, RGB);
//color c = color(0, 0, 0); // original code
color c = color(255, 255, 255); // it works now but I do not know why - and inverted color
// horizontal line
for(int i=0; i<width; i++){
img.set(i, height/2, c);
}
// vertical line
for(int i=0; i<height; i++){
img.set(width/2, i, c);
}
// diagonal line (TL-BR)
for(float i=0; i<width; i++){
img.set(int(i), int(i*slope), c);
}
// diagonal line (BL-TR)
for(float i=0; i<width; i++){
img.set(int(i), int(height-i*slope), c);
}
image(img, 0, 0);
By looking at some other examples online, for instance in the PImage tutorials found on the Processing site, I figured out what was going on. The original code does not work as intended with current Java and Processing. And, as per usual, making mistakes can often lead to figuring out how things work. Code placement in the sketch can affect how the sketch looks. Specifying the slope as a global variable did not work properly at this time and I ended up putting it in the draw function. The sketch could not find the height and width when slope was specified as a global variable.
And when using image(img, 0, 0), that places the image at the 0, 0 starting point. So, if you have an image that is less than the window size, you can see that it does not fill the whole window. This is what lead me to realize that the slope was not getting the correct values when it was initialized. It was a 1/1 slope when it should have been less. Below is the code that I ended up writing to work with this example:
/* program: p195_lines_with_pixels_3.pde
This program uses the PImage class to work with images. It allows for
direct manipulation
of pixles in the image. You can use an image from an external source or
create an image
in the sketch. Here, the image had to be created in the sketch.
This sketch was originally written as an example in Ira Greenberg's
book, "Processing:
Coding and Computational Art," 1st ed, 2007. So, the code had to be
changed a little, I
imagine because some things have changed with Java and Processing over
the years. The
current year is 2022. See the original code below */
// used by diagonal lines
// float slope = float(height)/float(width);
/* I think that part of the problem is that the image created below
actually creates an
image that is black, not a white background. So, the image created is
overlaying the
image of the background. Maybe the PImage class had a transparency to it
in 2007. */
//PImage img = createImage(width, height, RGB);
PImage img; // create img here, intialize it below
color c = color(0, 0, 0);
color cBackground = color(255, 255, 255);
void setup(){
size(500, 300);
background(255); // technically not necessary here as the image fills the window
}
void draw(){
// create the image called img
PImage img = createImage(width, height, RGB);
// fill the image with white pixels
float slope = float(height)/float(width);
for(int i=0; i<width; i++){
for(int j=0; j<height; j++){
img.set(i, j, cBackground);
}
}
// horizontal line
for(int i=0; i<width; i++){
img.set(i, height/2, c);
}
// vertical line
for(int i=0; i<height; i++){
img.set(width/2, i, c);
}
// diagonal line (TL-BR)
for(float i=0; i<width; i++){
img.set(int(i), int(i*slope), c);
}
// diagonal line (BL-TR)
for(float i=0; i<width; i++){
img.set(int(i), int(height-i*slope), c);
}
image(img, 0, 0);
}

Emgu CV draw rotated rectangle

I'm looking for few days a solution to draw rectangle on image frame. Basically I'm using CvInvoke.cvRectangle method to draw rectangle on image because I need antialiased rect.
But problem is when I need to rotate a given shape for given angle. I can't find any good solution.
I have tryed to draw rectangle on separate frame then rotate hole frame and apply this new image on top of my base frame. But in this solution there is a problem with antialiasing. It's not working.
I'm working on simple application that should allow draw few kinds of shape, resize them and rotation for given angle.
Any idea how to achive this?
The best way I found to draw a minimum enclosing rectangle on the contour is using the Polylines() function which uses vertices that are returned from MinAreaRect() function. There are surely other ways to do it as well. Here is the code walk down:
// Find contours
var contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
Mat hierarchy = new Mat();
CvInvoke.FindContours(image, contours, hierarchy, RetrType.Tree, ChainApproxMethod.ChainApproxSimple);
// According to your metric, get an index of the contour you want to find the min enclosing rectangle for
int index = 2; // Say, 2nd index works for you.
var rectangle = CvInvoke.MinAreaRect(contours[index]);
Point[] vertices = Array.ConvertAll(rectangle.GetVertices(), Point.Round);
CvInvoke.Polylines(image, vertices, true, new MCvScalar(0, 0, 255), 5);
The result can be visualized in the image below, in red is the minimum enclosing rectangle.
I use C# and EMGU.CV(4.1), and I think this code will not be difficult to transfer to any platform.
Add function in the in your helper:
public static Mat DrawRect(Mat input, RotatedRect rect, MCvScalar color = default(MCvScalar),
int thickness = 1, LineType lineType = LineType.EightConnected, int shift = 0)
{
var v = rect.GetVertices();
var prevPoint = v[0];
var firstPoint = prevPoint;
var nextPoint = prevPoint;
var lastPoint = nextPoint;
for (var i = 1; i < v.Length; i++)
{
nextPoint = v[i];
CvInvoke.Line(input, Point.Round(prevPoint), Point.Round(nextPoint), color, thickness, lineType, shift);
prevPoint = nextPoint;
lastPoint = prevPoint;
}
CvInvoke.Line(input, Point.Round(lastPoint), Point.Round(firstPoint), color, thickness, lineType, shift);
return input;
}
This draws roteted rectangle by points. Here used rounding points by method Point.Round becose RotatedRect has points in float coordinates and CvInvoke.Line takes points as integer.
Use:
var mat = Mat.Zeros(200, 200, DepthType.Cv8U, 3);
mat.GetValueRange();
var rRect = new RotatedRect(new PointF(100, 100), new SizeF(100, 50), 30);
DrawRect(mat, rRect,new MCvScalar(255,0,0));
var brect = CvInvoke.BoundingRectangle(new VectorOfPointF(rRect.GetVertices()));
CvInvoke.Rectangle(mat, brect, new MCvScalar(0,255,0), 1, LineType.EightConnected, 0);
Result:
You should read the OpenCV documentation.
There is a RotatedRectangle class that you can use for your task. You can specify the angle by which the rectangle will be rotated.
Here is a sample code (taken from the docs) for drawing a rotated rectangle:
Mat image(200, 200, CV_8UC3, Scalar(0));
RotatedRect rRect = RotatedRect(Point2f(100,100), Size2f(100,50), 30);
Point2f vertices[4];
rRect.points(vertices);
for (int i = 0; i < 4; i++)
line(image, vertices[i], vertices[(i+1)%4], Scalar(0,255,0));
Rect brect = rRect.boundingRect();
rectangle(image, brect, Scalar(255,0,0));
imshow("rectangles", image);
waitKey(0);
Here is the result:

pupil detection using opencv, with infrared image

I am trying the detect the pupil from a infrared image and calculate the center of the pupil.
In my setup, i used a camera sensitive to infrared light, and I added a visible light filter to the lens and two infrared LED around the camera.
However, the image I got is blur not so clear, maybe this caused by the low resolution of the camera, whose max is about 700x500.
In the processing, the first thing i did was to convert this RGB image to gray image, how ever the result is terrible. and it got nothing in the results.
int main()
{
//load image
cv::Mat src = cv::imread("11_13_2013_15_36_09.jpg");
cvNamedWindow("original");
cv::imshow("original", src);
cv::waitKey(10);
if (src.empty())
{
std::cout << "failed to find the image";
return -1;
}
// Invert the source image and convert to graysacle
cv::Mat gray;
cv::cvtColor(~src, gray, CV_BGR2GRAY);
cv::imshow("image1", gray);
cv::waitKey(10);
// Convert to binary image by thresholding it
cv::threshold(gray, gray, 220, 255, cv::THRESH_BINARY);
cv::imshow("image2", gray);
cv::waitKey(10);
// Find all contours
std::vector<std::vector<cv::Point>>contours;
cv::findContours(gray.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
// Fill holes in each contour
cv::drawContours(gray, contours, -1, CV_RGB(255, 255, 255), -1);
cv::imshow("image3", gray);
cv::waitKey(10);
for (int i = 0; i < contours.size(); i++)
{
double area = cv::contourArea(contours[i]);
cv::Rect rect = cv::boundingRect(contours[i]);
int radius = rect.width / 2;
// If controu is big enough and has round shape
// Then it is the pupil
if (area >= 800 &&
std::abs(1 - ((double)rect.width / (double)rect.height)) <= 0.3 &&
std::abs(1 - (area / (CV_PI * std::pow(radius, 2)))) <= 0.3)
{
cv::circle(src, cv::Point(rect.x + radius, rect.y + radius), radius, CV_RGB(255, 0, 0), 2);
}
}
cv::imshow("image", src);
cvWaitKey(0);
}
When the original image was converted, the gray image is terrible, does anyone know a better solution to this? I am completely new to this. for the rest of the code for finding the circle, if you have any comments, just tell me. and also i need to extra the position of the two glint (the light point) on the original image, does anyone has some idea?
thanks.
Try equalizing and filtering your source image before thresholding it ;)

Move around an image in processing

Is it possible to move an image (or image object) without clearing the whole background?
I wish to create an app that allows the user to "paint", using a device that is not the mouse. I would like to have a cursor to follow the users movement with the input device, without having to clear the already painted picture.
Is this possible? And how?
It depends how you handle drawing.
I would suggest using PImage as a canvas to draw into and another PImage to store the pixels of your brush. The 'brush' can be a loaded image, or at the start of your sketch you could make the brush using drawing commands, then store those as a PImage using get().
You will need to clear everything because you want to draw your cursor, but you will also draw your canvas, and you'll store 'brush strokes' only when the mouse is pressed (or some device specific method) by using the copy() or the blend() function (depending on your brush PNG - with or without transparency, etc.)
Here's a quick sketch to illustrate this:
PImage canvas;
PImage brush;
void setup(){
size(800,800);
stroke(128);
smooth();
canvas = createImage(width,height,ARGB);
brush = loadImage("brush.png");
}
void draw(){
background(255);
image(canvas,0,0);
//draw cursor
line(mouseX-5,mouseY-5,mouseX+5,mouseY+5);
line(mouseX+5,mouseY-5,mouseX-5,mouseY+5);
//blend brush pixels into canvas if mouse is pressed
if(mousePressed) canvas.blend(brush, 0, 0, brush.width, brush.width, (int)(mouseX-brush.width*.5), (int)(mouseY-brush.height*.5), brush.width, brush.width,MULTIPLY);
}
Note that you need an image into your sketch's data folder.
You can try it here:
You can run a javascript version bellow:
var canvas;
var brush;
function setup(){
createCanvas(800,800);
stroke(128);strokeWeight(3);
smooth();
canvas = createImage(width,height);
brush = getGradientImg(64,64,random(360),random(100),85);
}
function draw(){
background(255);
image(canvas,0,0);
//draw cursor
line(mouseX-5,mouseY-5,mouseX+5,mouseY+5);
line(mouseX+5,mouseY-5,mouseX-5,mouseY+5);
//blend brush pixels into canvas if mouse is pressed
if(isMousePressed) canvas.blend(brush, 0, 0, brush.width, brush.width, (int)(mouseX-brush.width*.5), (int)(mouseY-brush.height*.5), brush.width, brush.width,MULTIPLY);
//image(brush,mouseX,mouseY);
}
//*
function getGradientImg(w,h,hue,satMax,brightness){
push();//isolate drawing styles such as color Mode
colorMode(HSB,360,100,100);
var gradient = createImage(w,h);//create an image with an alpha channel
var np = w * h;//total number of pixels
var np4 = np*4;
var cx = floor(gradient.width * 0.5);//center on x
var cy = floor(gradient.height * 0.5);//center on y
gradient.loadPixels();
for(var i = 0 ; i < np4; i+=4){//for each pixel
var id4 = floor(i * .25);
var x = id4%gradient.width;//compute x from pixel index
var y = floor(id4/gradient.width);//compute y from pixel index
var d = dist(x,y,cx,cy);//compute distance from centre to current pixel
//map the saturation and transparency based on the distance to centre
gradient.pixels[i] = hue;
gradient.pixels[i+1] = map(d,0,cx,satMax,0);
gradient.pixels[i+2] = brightness;
gradient.pixels[i+3] = map(d,0,cx,255,0);
}
gradient.updatePixels();//finally update all the pixels
pop();
console.log(gradient);
return gradient;
}
//*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>

Qt-OpenCV:How to display grayscale images(opencv) in Qt

I have a piece of code here.
This is a camera capture application using OpenCV and Qt(for GUI).
void MainWindow::on_pushButton_clicked()
{
cv::VideoCapture cap(0);
if(!cap.isOpened()) return;
//namedWindow("edges",1);
QVector<QRgb> colorTable;
for (int i = 0; i < 256; i++) colorTable.push_back(qRgb(i, i, i));
QImage img;
img.setColorTable(colorTable);
for(;;)
{
cap >> image;
cvtColor(image, edges, CV_BGR2GRAY);
GaussianBlur(edges, edges, cv::Size(7,7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
//imshow("edges", edges);
if(cv::waitKey(30) >= 0) break;
// change color channel ordering
//cv::cvtColor(image,image,CV_BGR2RGB);
img = QImage((const unsigned char*)(edges.data),
image.cols,image.rows,QImage::Format_Indexed8);
// display on label
ui->label->setPixmap(QPixmap::fromImage(img,Qt::AutoColor));
// resize the label to fit the image
ui->label->resize(ui->label->pixmap()->size());
}
}
Initially "edges" is displayed in red with green background.Then it switches to blue background. This switching is happening randomly.
How can I display white edges in a black background in a stable manner.
In short, add the img.setColorTable(colorTable); just before the // display on labelcomment.
For more details, you create your image and affect the color table at the begining of your code:
QImage img;
img.setColorTable(colorTable);
Then in the infinite loop, you are doing the following:
img = QImage((const unsigned char*)(edges.data), image.cols, image.rows, QImage::Format_Indexed8);
What happens is that you destroy the image created at the begining of your code, the color map for this new image is not set and thus uses the default resulting in a colored output.

Resources