GAE images.resize with fixed proportional crop - google-app-engine

I need to resize and crop to exactly 60x80px from various size and
aspect ratio. Just before i put into Datastore. Anyone already got
this issue resolved.
Currently i already succed to just transform it to exact height (80px)
with various width which nott look so good when i try to display it on
a list. e.g jcaroussel.
My db.put code is like bellow:
if users.get_current_user():
personal.personal_id = int(self.request.get('personal_id'))
personal.name = self.request.get('name')
personal.latitude = self.request.get('latitude')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.lc_id = int(self.request.get('lc_id'))
personal.put()
self.redirect('/admin/personal')
else:
self.response.out.write('I\'m sorry, you don\'t have permission to add this LP Personal Data.')
I just want to do similar result when we upload our avatar on google
talk/google chat.
Anyone solved this?
Thx

After your resize your image down to 80 pixels in height, you would have to use the crop function as defined here. For example:
img = images.Image(self.request.get('img'))
img.resize(0, 80)
resized_img = img.execute_transforms(output_encoding=images.JPEG)
left_x = (resized_img.width - 60) / 2
resized_img.crop(left_x, 0, left_x + 60, 80)
cropped_img = resized_image.execute_transforms(output_encoding=images.JPEG)
In my example it crops to the center of the image.
It assumes that the resized image is at least 60 pixels wide, but obviously you would have to add some checks to confirm this, because a user might not upload an image in the right size.

I used something else:
Resize the original image to your max height (80)
Store the resized (but complete/not cropped) image
Display it inside a <div> that has the following CSS: width: 60px; height: 80px; overflow: hidden;
That way it will show nicely in your list, but you can still display the complete resized picture on your user's profile page (looking at you code I imagine that's what you are trying to do, right?)

Related

Problem with NumPy Arrays when creating Face Filters

I am currently working on a project where I detect a face with a haar cascade classifier.
In the code, I have created Rois with a cv2 rectangle and the goal is to apply images to the ROI. On some images the code works on others it doesn´t, also applying filters doesn´t work on videos or on my webcam.
The Error Code:
ValueError:
could not broadcast input array from the shape (50,70,3) into shape
(50,2,3)
Here are some code lines that may be important:
#Reading the image
image = file dialog.askopenfilename(initialdir="/Pictures", title="select a file", filetypes=(("png files", ".jpg", ),("all file", ".*")))
img = cv2.imread(image)
gray = np.array(img)
How the Roi is created and the filter applied.
visual_eye_r = cv2.rectangle(grayef, (x,y), (x+w, y+h), (255, 255, 255, 0), )
ROI_2 = visual_eye_r[y:y+h, x:x+w]
imagefilter = cv2.imread("filter.png")
roi_h, roi_w = ROI_2.shape[:2]
image_h, image_w = imagefilter.shape[:2]
#Calculate height and width offsets
height_off = int((roi_h - image_h)/2)
width_off = int((roi_w - image_w)/2)
#Mit Numpy Slicing Bild überlegen
ROI_2[height_off:height_off+image_h, width_off:width_off+image_w] = image8
Have already looked elsewhere for the same issue but none of the fixes worked. Maybe someone can help me understand or fix the issue, because i am relative new to python.
Issue has been fixed. Realised that the height and width offset was negative, because of the size of some Region of Interests. That was what caused the error.

How to get unlimited height for stage in Konva and compability issue with IE / Firefox

For my project I need to generate a konva page with a lot of nodes. User have to able to add new node and remove it. So far our productive data has around 8000 nodes. I work with angularJS and Konva. The pages must be work in Chrome, IE and Firefox. The codes look like this (modified because of company policy):
angular.module('testModule').controller('compabilityTestCtrl', [
function () {
var compabilityTestCtrl = this;
compabilityTestCtrl.stage = new Konva.Stage({
container: angular.element('<div>')[0],
width: 800,
height: 0
});
var layer = new Konva.Layer({});
var rect = new Konva.Rect({
x: 50,
y: 25,
width: 100,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 4
});
layer.add(rect);
compabilityTestCtrl.stage.height(rect.attrs.y + 50);
for (var i = 1; i < 436; i++) {
var newRect = rect.clone({
y: rect.attrs.y + (i * 75)
});
layer.add(newRect);
compabilityTestCtrl.stage.height(newRect.attrs.y + 75);
if (i == 435) {
console.log("Stage height is: " + compabilityTestCtrl.stage.getHeight());
}
}
compabilityTestCtrl.stage.add(layer);
angular.element('#compabilityTestKonva').append(compabilityTestCtrl.stage.content);
}]);
The problem is following:
1. As you can see, it can generate a node until a stage height of 32725px. If I add one more node (for-Loop to 437), the page will dissapeared (in Chrome). It can only generate until 436 nodes.
2. In Firefox, for 436 nodes the page is not totally generated. It just show 3/4 part of them. If I switched to safe-mode, it showed all of them. More than 436 nodes, it also dissapeared like in Chrome.
3. In IE, it just showed 1/4 of all nodes.
Questions:
Why I can not display all the pages in Firefox and IE?
Why the pages dissapeared if the stage getting bigger (in all browser), in this case.. more than 32725 px? Has Konva a limited height of stage?
I would be very happy for your suggestions.
I just wrote a fiddle, so you know what is actually the problem I have.
JSFiddle
In fiddle, it can generate up to 430 nodes (in Chrome), more than that I see only a blank page. In Firefox it ended on 353 nodes, and in IE it ended on 108 nodes.
The canvas element is like an image.
32725px height is super-duper huge. It will use a lot of resources.
Try to make a stage as small as possible. It will be better to make it not bigger than screen size. You can add some type of scrolling into the stage so users can see all objects.

How to control/scale image size in Codename One?

I used the (new) GUI Builder and inserted an image (by way of adding a Label). However, it appears too big. Is there anyway I can scale and control the size? (I saw something which points to cloudinary but that seems too complicated. I just want to simply scale down the image.)
There are several ways to resize images in Codename One and I will mention few below:
1.
Use MultiImages in the GUI Builder. With this multiple sizes of images are generated from one image based on the sizes you specified. In your GUI Builder, Click Images -> Add Multi Images -> Select your image -> Check Preserve Aspect Ratio -> Increase the % that represents the percentage of the screen width you want the image to occupy. Set any DPI you don't require to 0.
2.
Use ScaledImageLabel or ScaledImageButton, it will resize the image the fill available space the component is occupying.
3.
Scale the image itself in code (This is not efficient, though):
public static Image getImageFromTheme(String name) {
try {
Resources resFile = Resources.openLayered("/theme");
Image image = resFile.getImage(name);
return image;
} catch (IOException ioe) {
//Log.p("Image " + name + " not found: " + ioe);
}
return null;
}
Image resizedImage = getImageFromTheme("myImage").scaledWidth(Math.round(Display.getInstance().getDisplayWidth() / 10)); //change value as necessary
4.
Mutate the image (Create an image from another image).

Codename One rounded image from an internet source

I am trying to display a rounded image that I get straight from the Internet.
I used the code below to create a round mask, get the image from the Internet, then tried to either set the mask on the image or the label itself. None of these approaches worked. If I remove the mask, the image is displayed fine. If I keep the code to set the mask then all I see is an empty white circle.
I have the idea that if I apply the mask on the image itself, then it may not take effect because the image was not downloaded at the time the mask was applied.
But I don't seem to understand why calling setMask on the label is also not working.
// Create MASK
Image maskImage = Image.createImage(w, l);
Graphics g = maskImage.getGraphics();
g.setAntiAliased(true);
g.setColor(0x000000);
g.fillRect(0, 0, w, l);
g.setColor(0xffffff);
g.fillArc(0, 0, w, l, 0, 360);
Object mask = maskImage.createMask();
// GET IMAGE
com.cloudinary.Cloudinary cloudinary = new com.cloudinary.Cloudinary(ObjectUtils.asMap(
"cloud_name", "REMOVED",
"api_key", "REMOVED",
"api_secret", "REMOVED"));
// Disable private CDN URLs as this doesn't seem to work with free accounts
cloudinary.config.privateCdn = false;
Image placeholder = Image.createImage(150, 150);
EncodedImage encImage = EncodedImage.createFromImage(placeholder, false);
Image img2 = cloudinary.url()
.type("fetch") // Says we are fetching an image
.format("jpg") // We want it to be a jpg
.transformation(
new Transformation()
.radius("max").width(150).height(150).crop("thumb").gravity("faces").image(encImage, "http://upload.wikimedia.org/wikipedia/commons/4/46/Jennifer_Lawrence_at_the_83rd_Academy_Awards.jpg");
Label label = new Label(img2);
label.setMask(mask); // also tried to do img2.applyMask(mask); before passing img2
So I tried various things:
1) Removing the mask that was set through cloudinary - That did not work
2) applied the mask to the placeholder & encoded image (as expected these shouldnt affect the final version that is getting published)
3) This is what works! I am not sure if the issue is really with downloading the picture before or after applying the mask.. time can tell down the road
Label label = new Label();
img2.applyMask(mask); // If you remove this line , the image will no longer be displayed, I will only see a rounded white circle ! I am not sure what this is doing, it might be simply stalling the process until the image is downloaded? or maybe somehow calling repaint or revalidate
label.setIcon( img2.applyMask(mask));
Here is what worked for me if anyone else is having similar issues:
//CREATE MASK
Image maskImage = Image.createImage(w, l);
Graphics g = maskImage.getGraphics();
g.setAntiAliased(true);
g.setColor(0x000000);
g.fillRect(0, 0, w, l);
g.setColor(0xffffff);
g.fillArc(0, 0, w, l, 0, 360);
Object mask = maskImage.createMask();
//CONNECT TO CLOUDINARY
com.cloudinary.Cloudinary cloudinary = new com.cloudinary.Cloudinary(ObjectUtils.asMap(
"cloud_name", "REMOVED",
"api_key", "REMOVED",
"api_secret", "REMOVED"));
// Disable private CDN URLs as this doesn't seem to work with free accounts
cloudinary.config.privateCdn = false;
//CREATE IMAGE PLACEHOLDERS
Image placeholder = Image.createImage(w, l);
EncodedImage encImage = EncodedImage.createFromImage(placeholder, false);
//DOWNLOAD IMAGE
Image img2 = cloudinary.url()
.type("fetch") // Says we are fetching an image
.format("jpg") // We want it to be a jpg
.transformation(
new Transformation()
.crop("thumb").gravity("faces")
.image(encImage, url);
// Add the image to a label and place it on the form.
//GetCircleImage(img2);
Label label = new Label();
img2.applyMask(mask); // If you remove this line , the image will no longer be displayed, I will only see a rounded white circle ! I am not sure what this is doing, it might be simply stalling the process until the image is downloaded? or maybe somehow calling repaint or revalidate
label.setIcon( img2.applyMask(mask));
Shai, I seriously appreciate your time!! Thank you very much. Will have to dig more into it if it gives me any other problems later but it seems to consistently work for now.
The Cloudinary API returns a URLImage which doesn't work well with the Label.setMask() method because, technically, a URLImage is an animated image (it is a placeholder image until it finishes loading, and then "animates" to become the target image).
I have just released a new version of the cloudinary cn1lib which gives you a couple of options for working around this.
I have added two new image() methods. One that takes an ImageAdapter parameter that you can use to apply the mask to the image itself, before setting it as the icon for the label. Then you wouldn't use Label.setMask() at all.
See javadocs for this method here
The other method uses the new Async image loading APIs underneath to load the image asynchronously. The image you receive in the callback is a "real" image so you can use it with a mask normally.
See javadocs for this method here
We are looking at adding a soft warning to the Label.setMask() and setIcon() methods if you try to add an "animated" image and mask it so that it is more clear.
I think the making code you set to the label might be conflicting with the masking code you get from Cloudinary.

image array creating unwanted image in top corner

I have this set up in my main.lua file
images = {
display.newImageRect("images/player3.png", 45,35),
display.newImageRect("images/player4.png", 45,35),
display.newImageRect("images/player5.png", 45,35)
}
and call it from my game.lua file with this code:
bird = images[math.random(1,3)]
bird.x, bird.y = -80, 140
bird.name = "bird"
physics.addBody( bird, "static")
bird.isFixedRotation = true
birdIntro = transition.to(bird,{time=1000, x=100, onComplete= birdReady})
A random image spawns (where it should, in the middle) but the issue is that a second image spawns and sits in the top left corner of the screen (slightly off screen). I can't seem to remove it and keep the one correct image only, any solutions?
Your help is greatly appreciated.
Thanks
I think the problem is your images array. I've found by calling the display.newImageRect it will create the object and plop it on the screen. Even if you don't want it to show the object right then. Usually I see this when I should be putting it in a display group (not sure if you are doing that).
I think the solution might be to have the array of images be the image paths and then you can set bird equal to a new image rect at that point, thus only creating 1 image rectangle instead of 3.
images = {
"images/player3.png",
"images/player4.png",
"images/player5.png",
}
bird = display.newImageRect(images[math.random(1,3)],45,35)
Let me know if that works.

Resources