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

  • Python Multimedia
  • Ninad Sathaye
  • 431字
  • 2021-08-03 15:27:41

Time for action – pasting: mirror the smiley face!

Consider the example in earlier section where we cropped a region of an image. The cropped region contained a smiley face. Let's modify the original image so that it has a 'reflection' of the smiley face.

  1. If not already, download the file Crop.png from the Packt website.
  2. Write this code by replacing the file path with appropriate file path on your system.
    1 import Image
    2 img = Image.open("C:\\images\\Crop.png")
    3 # Define the elements of a 4-tuple that represents
    4 # a bounding box ( region to be cropped)
    5 left = 0
    6 upper = 25
    7 right = 180
    8 lower = 210
    9 bbox = (left, upper, right, lower)
    10 # Crop the smiley face from the image
    11 smiley = img.crop(bbox_1)
    12 # Flip the image horizontally
    13 smiley = smiley.transpose(Image.FLIP_TOP_BOTTOM)
    14 # Define the box as a 2-tuple.
    15 bbox_2 = (0, 210)
    16 # Finally paste the 'smiley' on to the image.
    17 img.paste(smiley, bbox_2)
    18 img.save("C:\\images\\Pasted.png")
    19 img.show()
  3. First we open an image and crop it to extract a region containing the smiley face. This was already done in section Error: Reference source not found'Cropping'. The only minor difference you will notice is the value of the tuple element upper. It is intentionally kept as 25 pixels from the top to make sure that the crop image has a size that can fit in the blank portion below the original smiley face.
  4. The cropped image is then flipped horizontally with code on line 13.
  5. Now we define a box, bbox_2, for pasting the cropped smiley face back on to the original image. Where should it be pasted? We intend to make a 'reflection' of the original smiley face. So the coordinate of the top-right corner of the pasted image should be greater than or equal to the bottom y coordinate of the cropped region, indicated by 'lower' variable (see line 8) . The bounding box is defined on line 15, as a 2-tuple representing the upper-left coordinates of the smiley.
  6. Finally, on line 17, the paste operation is performed to paste the smiley on the original image. The resulting image is then saved with a different name.
  7. The original image and the output image after the paste operation is shown in the next illustration.

The illustration shows the comparison of original and resulting images after the paste operation.

What just happened?

Using a combination of Image.crop and Image.paste, we accomplished cropping a region, making some modifications, and then pasting the region back on the image.

主站蜘蛛池模板: 精河县| 大埔区| 会同县| 崇仁县| 新乡市| 同江市| 枣强县| 基隆市| 太康县| 林州市| 邮箱| 庆城县| 大同市| 德江县| 疏勒县| 江津市| 江阴市| 贵定县| 九江县| 南康市| 九龙县| 扶沟县| 东城区| 辽中县| 隆昌县| 北票市| 桂平市| 福州市| 满洲里市| 镇江市| 岱山县| 电白县| 土默特左旗| 朝阳县| 昌都县| 吉安市| 黄山市| 吉首市| 夏邑县| 和平县| 章丘市|