官术网_书友最值得收藏!

  • Python Multimedia
  • Ninad Sathaye
  • 271字
  • 2021-08-03 15:27:40

Time for action – flipping

Imagine that you are building a symmetric image using a bunch of basic shapes. To create such an image, an operation that can flip (or mirror) the image would come in handy. So let's see how image flipping can be accomplished.

  1. Write the following code in a Python source file.
    1 import Image
    2 inPath = "C:\\images\\Flip.png"
    3 img = Image.open(inPath)
    4 outPath = "C:\\images\\Flip_out.png"
    5 foo = img.transpose(Image.FLIP_LEFT_RIGHT)
    6 foo.save(outPath)
  2. In this code, the image is flipped horizontally by calling the transpose method. To flip the image vertically, replace line 5 in the code with the following:
    foo = img.transpose(Image.FLIP_TOP_BOTTOM)
  3. The following illustration shows the output of the preceding code when the image is flipped horizontally and vertically.
  4. The same effect can be achieved using the ImageOps module. To flip the image horizontally, use ImageOps.mirror, and to flip the image vertically, use ImageOps.flip.
    import ImageOps
    
    # Flip image horizontally
    foo1 = ImageOps.mirror(img)
    # Flip image vertically
    foo2 = ImageOps.flip(img)

What just happened?

With the help of example, we learned how to flip an image horizontally or vertically using Image.transpose and also by using methods in class ImageOps. This operation will be applied later in this book for further image processing such as preparing composite images.

Capturing screenshots

How do you capture the desktop screen or a part of it using Python? There is ImageGrab module in PIL. This simple line of code will capture the whole screen.

img = ImageGrab.grab()

Where, img is an instance of class Image.

However, note that in PIL Version 1.1.6, the ImageGrab module supports screen grabbing only for Windows platform.

主站蜘蛛池模板: 大新县| 儋州市| 睢宁县| 诸城市| 武强县| 乌拉特后旗| 沂源县| 柳林县| 邹城市| 搜索| 宜阳县| 伊春市| 全南县| 商洛市| 瓦房店市| 福泉市| 石家庄市| 阜新市| 云霄县| 天柱县| 安徽省| 平顶山市| 辉南县| 三亚市| 锦屏县| 津南区| 周宁县| 清水县| 长沙市| 临湘市| 广河县| 和静县| 晋城| 来凤县| 遂溪县| 田东县| 安福县| 蒙阴县| 天峨县| 湛江市| 泰兴市|