Imagick Imagick::mosaicImages (void)Parameters:This function takes no parameters.Returned value:This function returns TRUE on success.The program below illustrates the function Imagick::mosaicImages() in PHP:Program:
// Create a new Imagick object
$imagick
=
new
Imagick ( );
// Set width, height and background
// image color
$imagick
-> newimage (500, 200,
’green’
);
// Save images in an array
$imagesArray
= [
" https://media.engineerforengineer.org/wp-content/ uploads / 20190823154611 / engineerforengineer24.png "
,
" https://media.engineerforengineer.org/wp-content/uploads/ 20190826132815 / download7.png "
];
// Set the position of each image
$positionsArray
= [
[0, 0],
[0, 100]
];
// Add images from multiple settings pages
for
(
$i
= 0;
$i
< 2;
$i
++) {
$nextImage
=
new
Imagick (
$imagesArray
[
$i
]);
$nextImage
-> resizeimage (300, 300, Imagick::FILTER_LANCZOS, 1.0, true);
$nextImage
-> setImagePage (
$nextImage
-> getImageWidth(),
$nextImage
-> getImageHeight(),
$positionsArray
[
$i
] [0],
$positionsArray
[
$i
] [1]
);
$imagick
-> addImage (
$nextImage
);
}
// Use the mosaicImages() function
$result
=
$imagick
-> mosaicImages();
// Set image format
$result
-> setImageFormat (
’png’
);
header (
" Content-Type: image / png "
);
// Display the output image
echo
$result
-> getImageBlob();
?>
Output: Link: https://www.php.net/manual/en/imagick.mosaicimages.php
PHP Imagick mosaicImages () function: StackOverflow Questions
List comprehension vs. lambda + filter
I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.
My code looked like this:
my_list = [x for x in my_list if x.attribute == value]
But then I thought, wouldn"t it be better to write it like this?
my_list = filter(lambda x: x.attribute == value, my_list)
It"s more readable, and if needed for performance the lambda could be taken out to gain something.
Question is: are there any caveats in using the second way? Any performance difference? Am I missing the Pythonic Way‚Ñ¢ entirely and should do it in yet another way (such as using itemgetter instead of the lambda)?
Answer #1:
It is strange how much beauty varies for different people. I find the list comprehension much clearer than filter
+lambda
, but use whichever you find easier.
There are two things that may slow down your use of filter
.
The first is the function call overhead: as soon as you use a Python function (whether created by def
or lambda
) it is likely that filter will be slower than the list comprehension. It almost certainly is not enough to matter, and you shouldn"t think much about performance until you"ve timed your code and found it to be a bottleneck, but the difference will be there.
The other overhead that might apply is that the lambda is being forced to access a scoped variable (value
). That is slower than accessing a local variable and in Python 2.x the list comprehension only accesses local variables. If you are using Python 3.x the list comprehension runs in a separate function so it will also be accessing value
through a closure and this difference won"t apply.
The other option to consider is to use a generator instead of a list comprehension:
def filterbyvalue(seq, value):
for el in seq:
if el.attribute==value: yield el
Then in your main code (which is where readability really matters) you"ve replaced both list comprehension and filter with a hopefully meaningful function name.
Answer #2:
This is a somewhat religious issue in Python. Even though Guido considered removing map
, filter
and reduce
from Python 3, there was enough of a backlash that in the end only reduce
was moved from built-ins to functools.reduce.
Personally I find list comprehensions easier to read. It is more explicit what is happening from the expression [i for i in list if i.attribute == value]
as all the behaviour is on the surface not inside the filter function.
I would not worry too much about the performance difference between the two approaches as it is marginal. I would really only optimise this if it proved to be the bottleneck in your application which is unlikely.
Also since the BDFL wanted filter
gone from the language then surely that automatically makes list comprehensions more Pythonic ;-)
How do I do a not equal in Django queryset filtering?
Question by MikeN
In Django model QuerySets, I see that there is a __gt
and __lt
for comparative values, but is there a __ne
or !=
(not equals)? I want to filter out using a not equals. For example, for
Model:
bool a;
int x;
I want to do
results = Model.objects.exclude(a=True, x!=5)
The !=
is not correct syntax. I also tried __ne
.
I ended up using:
results = Model.objects.exclude(a=True, x__lt=5).exclude(a=True, x__gt=5)
Answer #1:
You can use Q objects for this. They can be negated with the ~
operator and combined much like normal Python expressions:
from myapp.models import Entry
from django.db.models import Q
Entry.objects.filter(~Q(id=3))
will return all entries except the one(s) with 3
as their ID:
[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]
Answer #2:
Your query appears to have a double negative, you want to exclude all rows where x
is not 5, so in other words you want to include all rows where x
is 5. I believe this will do the trick:
results = Model.objects.filter(x=5).exclude(a=True)
To answer your specific question, there is no "not equal to" field lookup but that"s probably because Django has both filter
and exclude
methods available so you can always just switch the logic around to get the desired result.
Answer #3:
the field=value
syntax in queries is a shorthand for field__exact=value
. That is to say that Django puts query operators on query fields in the identifiers. Django supports the following operators:
exact
iexact
contains
icontains
in
gt
gte
lt
lte
startswith
istartswith
endswith
iendswith
range
date
year
iso_year
month
day
week
week_day
iso_week_day
quarter
time
hour
minute
second
isnull
regex
iregex
I"m sure by combining these with the Q objects as Dave Vogt suggests and using filter()
or exclude()
as Jason Baker suggests you"ll get exactly what you need for just about any possible query.
PHP Imagick mosaicImages () function: StackOverflow Questions
How do I resize an image using PIL and maintain its aspect ratio?
Question by saturdayplace
Is there an obvious way to do this that I"m missing? I"m just trying to make thumbnails.
Answer #1:
Define a maximum size.
Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height)
.
The proper size is oldsize*ratio
.
There is of course also a library method to do this: the method Image.thumbnail
.
Below is an (edited) example from the PIL documentation.
import os, sys
import Image
size = 128, 128
for infile in sys.argv[1:]:
outfile = os.path.splitext(infile)[0] + ".thumbnail"
if infile != outfile:
try:
im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)
im.save(outfile, "JPEG")
except IOError:
print "cannot create thumbnail for "%s"" % infile
Answer #2:
This script will resize an image (somepic.jpg) using PIL (Python Imaging Library) to a width of 300 pixels and a height proportional to the new width. It does this by determining what percentage 300 pixels is of the original width (img.size[0]) and then multiplying the original height (img.size[1]) by that percentage. Change "basewidth" to any other number to change the default width of your images.
from PIL import Image
basewidth = 300
img = Image.open("somepic.jpg")
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save("somepic.jpg")
How to resize an image with OpenCV2.0 and Python2.6
I want to use OpenCV2.0 and Python2.6 to show resized images. I used and adopted this example but unfortunately, this code is for OpenCV2.1 and does not seem to be working on 2.0. Here my code:
import os, glob
import cv
ulpath = "exampleshq/"
for infile in glob.glob( os.path.join(ulpath, "*.jpg") ):
im = cv.LoadImage(infile)
thumbnail = cv.CreateMat(im.rows/10, im.cols/10, cv.CV_8UC3)
cv.Resize(im, thumbnail)
cv.NamedWindow(infile)
cv.ShowImage(infile, thumbnail)
cv.WaitKey(0)
cv.DestroyWindow(name)
Since I cannot use
cv.LoadImageM
I used
cv.LoadImage
instead, which was no problem in other applications. Nevertheless, cv.iplimage has no attribute rows, cols or size. Can anyone give me a hint, how to solve this problem?
Answer #1:
If you wish to use CV2, you need to use the resize
function.
For example, this will resize both axes by half:
small = cv2.resize(image, (0,0), fx=0.5, fy=0.5)
and this will resize the image to have 100 cols (width) and 50 rows (height):
resized_image = cv2.resize(image, (100, 50))
Another option is to use scipy
module, by using:
small = scipy.misc.imresize(image, 0.5)
There are obviously more options you can read in the documentation of those functions (cv2.resize, scipy.misc.imresize).
Update:
According to the SciPy documentation:
imresize
is deprecated in SciPy 1.0.0, and
will be removed in 1.2.0.
Use skimage.transform.resize
instead.
Note that if you"re looking to resize by a factor, you may actually want skimage.transform.rescale
.
Answer #2:
Example doubling the image size
There are two ways to resize an image. The new size can be specified:
Manually;
height, width = src.shape[:2]
dst = cv2.resize(src, (2*width, 2*height), interpolation = cv2.INTER_CUBIC)
By a scaling factor.
dst = cv2.resize(src, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC)
,
where fx is the scaling factor along the horizontal axis and fy along the vertical axis.
To shrink an image, it will generally look best with INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with INTER_CUBIC (slow) or INTER_LINEAR (faster but still looks OK).
Example shrink image to fit a max height/width (keeping aspect ratio)
import cv2
img = cv2.imread("YOUR_PATH_TO_IMG")
height, width = img.shape[:2]
max_height = 300
max_width = 300
# only shrink if img is bigger than required
if max_height < height or max_width < width:
# get scaling factor
scaling_factor = max_height / float(height)
if max_width/float(width) < scaling_factor:
scaling_factor = max_width / float(width)
# resize image
img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
cv2.imshow("Shrinked image", img)
key = cv2.waitKey()
Using your code with cv2
import cv2 as cv
im = cv.imread(path)
height, width = im.shape[:2]
thumbnail = cv.resize(im, (round(width / 10), round(height / 10)), interpolation=cv.INTER_AREA)
cv.imshow("exampleshq", thumbnail)
cv.waitKey(0)
cv.destroyAllWindows()
Numpy Resize/Rescale Image
I would like to take an image and change the scale of the image, while it is a numpy array.
For example I have this image of a coca-cola bottle:
bottle-1
Which translates to a numpy array of shape (528, 203, 3)
and I want to resize that to say the size of this second image:
bottle-2
Which has a shape of (140, 54, 3)
.
How do I change the size of the image to a certain shape while still maintaining the original image? Other answers suggest stripping every other or third row out, but what I want to do is basically shrink the image how you would via an image editor but in python code. Are there any libraries to do this in numpy/SciPy?
Answer #1:
Yeah, you can install opencv
(this is a library used for image processing, and computer vision), and use the cv2.resize
function. And for instance use:
import cv2
import numpy as np
img = cv2.imread("your_image.jpg")
res = cv2.resize(img, dsize=(54, 140), interpolation=cv2.INTER_CUBIC)
Here img
is thus a numpy array containing the original image, whereas res
is a numpy array containing the resized image. An important aspect is the interpolation
parameter: there are several ways how to resize an image. Especially since you scale down the image, and the size of the original image is not a multiple of the size of the resized image. Possible interpolation schemas are:
INTER_NEAREST
- a nearest-neighbor interpolation
INTER_LINEAR
- a bilinear interpolation (used by default)
INTER_AREA
- resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free
results. But when the image is zoomed, it is similar to the
INTER_NEAREST
method.
INTER_CUBIC
- a bicubic interpolation over 4x4 pixel neighborhood
INTER_LANCZOS4
- a Lanczos interpolation over 8x8 pixel neighborhood
Like with most options, there is no "best" option in the sense that for every resize schema, there are scenarios where one strategy can be preferred over another.