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

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

Time for action – cropping an image

This simple code snippet crops an image and applies some changes on the cropped portion.

  1. Download the file Crop.png from Packt website. The size of this image is 400 x 400 pixels. You can also use your own image file.
  2. Write the following code in a Python source file. Modify the path of the image file to an appropriate path.
    import Image
    img = Image.open("C:\\images\\Crop.png")
    left = 0
    upper = 0
    right = 180
    lower = 215
    bbox = (left, upper, right, lower)
    img = img.crop(bbox)
    img.show()
  3. This will crop a region of the image bounded by bbox. The specification of the bounding box is identical to what we have seen in the Capturing screenshots section. The output of this example is shown in the following illustration.

    Original image (left) and its cropped region (right).

What just happened?

In the previous section, we used Image.crop functionality to crop a region within an image and save the resultant image. In the next section, we will apply this while pasting a region of an image onto another.

Pasting

Pasting a copied or cut image onto another one is a commonly performed operation while processing images. Following is the simplest syntax to paste one image on another.

img = img.paste(image, box)

Here image is an instance of class Image and box is a rectangular bounding box that defines the region of img, where the image will be pasted. The box argument can be a 4-tupleError: Reference source not found or a 2-tuple. If a 4-tuple box is specified, the size of the image to be pasted must be same as the size of the region. Otherwise, PIL will throw an error with a message ValueError: images do not match. The 2-tuple on the other hand, provides pixel coordinates of the upper-left corner of the region to be pasted.

Now look at the following line of code. It is a copy operation on an image.

img2 = img.copy(image)

The copy operation can be viewed as pasting the whole image onto a new image. This operation is useful when, for instance, you want to keep the original image unaltered and make alterations to the copy of the image.

主站蜘蛛池模板: 华亭县| 醴陵市| 陆河县| 大足县| 来宾市| 农安县| 乾安县| 常宁市| 涞源县| 类乌齐县| 民县| 灵丘县| 工布江达县| 张家界市| 小金县| 历史| 通渭县| 凌源市| 平安县| 全州县| 阳高县| 清丰县| 浦县| 册亨县| 图们市| 安平县| 阜新市| 阜南县| 新营市| 黄浦区| 张家港市| 龙南县| 广东省| 易门县| 鄄城县| 墨江| 黎川县| 铜山县| 周口市| 商河县| 都安|