👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
I am trying to horizontally combine some JPEG images in Python.
I have 3 images - each is 148 x 95 - see attached. I just made 3 copies of the same image - that is why they are the same.
I am trying to horizontally join them using the following code:
import sys from PIL import Image list_im = ["Test1.jpg","Test2.jpg","Test3.jpg"] # creates a new empty image, RGB mode, and size 444 by 95 new_im = Image.new("RGB", (444,95)) for elem in list_im: for i in xrange(0,444,95): im=Image.open(elem) new_im.paste(im, (i,0)) new_im.save("test.jpg")
However, this is producing the output attached as
Is there a way to horizontally concatenate these images such that the sub-images in test.jpg do not have an extra partial image showing?
I am looking for a way to horizontally concatenate n images. I would like to use this code generally so I would prefer to:
- not to hard-code image dimensions, if possible
- specify dimensions in one line so that they can be easily changed
👻 Read also: what is the best laptop for engineering students?
Combine several images horizontally with Python join: Questions
Why is it string.join(list) instead of list.join(string)?
This has always confused me. It seems like this would be nicer:
my_list = ["Hello", "world"] print(my_list.join("-")) # Produce: "Hello-world"
my_list = ["Hello", "world"] print("-".join(my_list)) # Produce: "Hello-world"
Is there a specific reason it is like this?
It"s because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the "joiner" must be strings.
"_".join(["welcome", "to", "stack", "overflow"]) "_".join(("welcome", "to", "stack", "overflow"))
Using something other than strings will raise the following error:
TypeError: sequence item 0: expected str instance, int found
This was discussed in the String methods... finally thread in the Python-Dev achive, and was accepted by Guido. This thread began in Jun 1999, and
str.join was included in Python 1.6 which was released in Sep 2000 (and supported Unicode). Python 2.0 (supported
str methods including
join) was released in Oct 2000.
- There were four options proposed in this thread:
joinas a built-in function
- Guido wanted to support not only
tuples, but all sequences/iterables.
seq.reduce(str)is difficult for newcomers.
seq.join(str)introduces unexpected dependency from sequences to str/unicode.
join()as a built-in function would support only specific data types. So using a built-in namespace is not good. If
join()supports many datatypes, creating an optimized implementation would be difficult, if implemented using the
__add__method then it would ve
- The separator string (
sep) should not be omitted. Explicit is better than implicit.
Here are some additional thoughts (my own, and my friend"s):
- Unicode support was coming, but it was not final. At that time UTF-8 was the most likely about to replace UCS2/4. To calculate total buffer length of UTF-8 strings it needs to know character coding rule.
- At that time, Python had already decided on a common sequence interface rule where a user could create a sequence-like (iterable) class. But Python didn"t support extending built-in types until 2.2. At that time it was difficult to provide basic
iterableclass (which is mentioned in another comment).
Guido"s decision is recorded in a historical mail, deciding on
Funny, but it does seem right! Barry, go for it...
Guido van Rossum
join() method is in the string class, instead of the list class?
I agree it looks funny.
Historical note. When I first learned Python, I expected join to be a method of a list, which would take the delimiter as an argument. Lots of people feel the same way, and there‚Äôs a story behind the join method. Prior to Python 1.6, strings didn‚Äôt have all these useful methods. There was a separate string module which contained all the string functions; each function took a string as its first argument. The functions were deemed important enough to put onto the strings themselves, which made sense for functions like lower, upper, and split. But many hard-core Python programmers objected to the new join method, arguing that it should be a method of the list instead, or that it shouldn‚Äôt move at all but simply stay a part of the old string module (which still has lots of useful stuff in it). I use the new join method exclusively, but you will see code written either way, and if it really bothers you, you can use the old string.join function instead.
--- Mark Pilgrim, Dive into Python
How can I open multiple files using "with open" in Python?
I want to change a couple of files at one time, iff I can write to all of them. I"m wondering if I somehow can combine the multiple open calls with the
try: with open("a", "w") as a and open("b", "w") as b: do_something() except IOError as e: print "Operation failed: %s" % e.strerror
If that"s not possible, what would an elegant solution to this problem look like?
As of Python 2.7 (or 3.1 respectively) you can write
with open("a", "w") as a, open("b", "w") as b: do_something()
In earlier versions of Python, you can sometimes use
contextlib.nested() to nest context managers. This won"t work as expected for opening multiples files, though -- see the linked documentation for details.
In the rare case that you want to open a variable number of files all at the same time, you can use
contextlib.ExitStack, starting from Python version 3.3:
with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in filenames] # Do something with "files"
Most of the time you have a variable set of files, you likely want to open them one after the other, though.
open() in Python does not create a file if it doesn"t exist
What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read,
file = open("myfile.dat", "rw") should do this, right?
It is not working for me (Python 2.6.2) and I"m wondering if it is a version problem, or not supposed to work like that or what.
The bottom line is, I just need a solution for the problem. I am curious about the other stuff, but all I need is a nice way to do the opening part.
The enclosing directory was writeable by user and group, not other (I"m on a Linux system... so permissions 775 in other words), and the exact error was:
IOError: no such file or directory.
You should use
open with the
file = open("myfile.dat", "w+")
Difference between modes a, a+, w, w+, and r+ in built-in open function?
In the python built-in open function, what is the exact difference between the modes
In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, but does not define what these terms mean.
The opening modes are exactly the same as those for the C standard library function
fopen manpage defines them as follows:
The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.): ``r"" Open text file for reading. The stream is positioned at the beginning of the file. ``r+"" Open for reading and writing. The stream is positioned at the beginning of the file. ``w"" Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file. ``w+"" Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. ``a"" Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar. ``a+"" Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.
We hope this article has helped you to resolve the problem. Apart from Combine several images horizontally with Python, check other join-related topics.
By the way, this material is also available in other languages:
- Italiano Combine several images horizontally with Python
- Deutsch Combine several images horizontally with Python
- Français Combine several images horizontally with Python
- Español Combine several images horizontally with Python
- Türk Combine several images horizontally with Python
- Русский Combine several images horizontally with Python
- Português Combine several images horizontally with Python
- Polski Combine several images horizontally with Python
- Nederlandse Combine several images horizontally with Python
- 中文 Combine several images horizontally with Python
- 한국어 Combine several images horizontally with Python
- 日本語 Combine several images horizontally with Python
- हिन्दी Combine several images horizontally with Python
Vigrinia | 2022-11-30
Thanks for explaining! I was stuck with Combine several images horizontally with Python for some hours, finally got it done 🤗. I am just not quite sure it is the best method
Shanghai | 2022-11-30
join is always a bit confusing 😭 Combine several images horizontally with Python is not the only problem I encountered. I just hope that will not emerge anymore
Tallinn | 2022-11-30
Thanks for explaining! I was stuck with Combine several images horizontally with Python for some hours, finally got it done 🤗. Will get back tomorrow with feedback