1

In this link, I found the following line of code:

image = Image.open("testOCR3.png")\
        .convert('L').resize([3 * _ for _ in image.size], Image.BICUBIC)\
        .point(lambda p: p > 75 and p + 100)

Unfortunately, I just don't understand it yet.

(i) What does \ do? And why is it used at all?

(ii) Also, according to the documentation:

Image.convert(mode=None, matrix=None, dither=None, palette=0, colors=256). 

So why does .convert().resize() work?

Thanks in advance!

3 Answers3

1

I don't understand what the second question is, but the first:

my_str = "the backslash" \
         "operator let's you" \
         "split things across" \
         "lines" 

As it happened I've never seen it before for splitting dot notation, but hey you learn something new.

Alan
  • 1,746
  • 7
  • 21
1

In Python, a statement ends when a new line is encountered. Backslash just tells the Python interpreter that the statement continues on the next line.

0

The code you posted is an example of chaining multiple methods of an object together.
The backslash just tells the python interpreter that the code continues in the next line. Instead of the backslash you could also write:

image = Image.open("testOCR3.png")
image = image.convert('L').resize([3 * _ for _ in image.size], Image.BICUBIC)
image = image.point(lambda p: p > 75 and p + 100)

To Explain (and maybe also answer your (ii)):
The first method Image.open returns an image object (or instance), which again has methods like .convert('L'). The convert method is executed and does (probably) a conversion in some form and returns again an image object, that as before has it's own designated methods.

According to the docs you referenced the .convert() method of an Image object does return the following:

Return type: Image

Björn
  • 1,610
  • 2
  • 17
  • 37
  • 1
    Okay, thank you for your line of code! As a newbie, I was confused by the \. I think I can now answer (ii) myself, since the following line of code works as well: *image = image.convert('L') image = image.resize(...)* –  Apr 05 '20 at 12:59
  • 1
    The backslash has absolutely nothing to do with chaining method calls! This is very misleading. – deceze Apr 05 '20 at 14:18
  • @deceze the backslash in the provided example contributes to chaining the method calls. It is used to span the method chaining over 3 lines of code. – Björn Apr 05 '20 at 14:34
  • 1
    [Jein](https://www.urbandictionary.com/define.php?term=jein). Without the backslash it wouldn't work, but that's because you'd end up with a syntax error instead. The backslash is only relevant to the syntax, it contributes nothing to the method chain. Your updated answer is more acceptable. – deceze Apr 05 '20 at 14:37