Convert Images using Python Image Processing Library
Converting Images to Black n White and Grayscale
Sometimes you may require to convert colored images to Black n White or Grayscale for printing or archiving purposes. This article demonstrates the use of Aspose.Imaging for Python via .NET API to achieve this using two methods as stated below.
- Binarization
- Grayscaling
Binarization
In order to understand the concept of Binarization, it is important to define a Binary Image; that is a digital image that can have only two possible values for each pixel. Normally, the two colors used for a binary image are black and white though any two colors can be used. Binarization is the process of converting an image to bi-level meaning that each pixel is stored as a single bit (0 or 1) where 0 denotes the absence of color and 1 means presence of color. Aspose.Imaging for Python via .NET API currently supports two Binarization methods.
Binarization with Fixed Threshold
The following code snippet shows you how to use fixed threshold binarization can be applied to an image.
import aspose.pycore as aspycore | |
from aspose.imaging import RasterCachedImage, Image | |
import os | |
if 'TEMPLATE_DIR' in os.environ: | |
templates_folder = os.environ['TEMPLATE_DIR'] | |
else: | |
templates_folder = r"C:\Users\USER\Downloads\templates" | |
delete_output = 'SAVE_OUTPUT' not in os.environ | |
data_dir = templates_folder | |
# Load an image in an instance of Image | |
with Image.load(os.path.join(data_dir, "template.jpg")) as image: | |
# Cast the image to RasterCachedImage and Check if image is cached | |
raster_cached_image = aspycore.as_of(image, RasterCachedImage) | |
if not raster_cached_image.is_cached: | |
# Cache image if not already cached | |
raster_cached_image.cache_data() | |
# Binarize image with predefined fixed threshold and Save the resultant image | |
raster_cached_image.binarize_fixed(100) | |
raster_cached_image.save(os.path.join(data_dir, "result.jpg")) | |
if delete_output: | |
os.remove(os.path.join(data_dir, "result.jpg")) |
Binarization with Otsu Threshold
The following code snippet shows you how Otsu threshold binarization can be applied to an image.
import aspose.pycore as aspycore | |
from aspose.imaging import RasterCachedImage, Image | |
import os | |
if 'TEMPLATE_DIR' in os.environ: | |
templates_folder = os.environ['TEMPLATE_DIR'] | |
else: | |
templates_folder = r"C:\Users\USER\Downloads\templates" | |
delete_output = 'SAVE_OUTPUT' not in os.environ | |
data_dir = templates_folder | |
# Load an image in an instance of Image | |
with Image.load(os.path.join(data_dir, "template.jpg")) as image: | |
# Cast the image to RasterCachedImage and Check if image is cached | |
raster_cached_image = aspycore.as_of(image, RasterCachedImage) | |
if not raster_cached_image.is_cached: | |
# Cache image if not already cached | |
raster_cached_image.cache_data() | |
# Binarize image with predefined fixed threshold and Save the resultant image | |
raster_cached_image.binarize_otsu() | |
raster_cached_image.save(os.path.join(data_dir, "result.jpg")) | |
if delete_output: | |
os.remove(os.path.join(data_dir, "result.jpg")) |
Grayscaling
Gray-scaling is the process of converting a continuous-tone image to an image with discontinues gray shades. The following code snippet shows you how to use Grayscaling.
import aspose.pycore as aspycore | |
from aspose.imaging import * | |
import os | |
if 'TEMPLATE_DIR' in os.environ: | |
templates_folder = os.environ['TEMPLATE_DIR'] | |
else: | |
templates_folder = r"C:\Users\USER\Downloads\templates" | |
delete_output = 'SAVE_OUTPUT' not in os.environ | |
data_dir = templates_folder | |
# Load an image in an instance of Image | |
with Image.load(os.path.join(data_dir, "template.jpg")) as image: | |
# Cast the image to RasterCachedImage and check if image is cached | |
raster_cached_image = aspycore.as_of(image, RasterCachedImage) | |
if not raster_cached_image.is_cached: | |
# Cache image if not already cached | |
raster_cached_image.cache_data() | |
# Convert the image in grayscale and save the resultant image | |
raster_cached_image.grayscale() | |
raster_cached_image.save(os.path.join(data_dir, "result.jpg")) | |
if delete_output: | |
os.remove(os.path.join(data_dir, "result.jpg")) |
Convert Image to grayscale with Setting 16bit
Gray-scaling is the process of converting a continuous-tone image to an image with discontinues gray shades. The following code snippet shows you how to use Grayscaling with 16bits.
import aspose.pycore as aspycore | |
from aspose.imaging import * | |
import os | |
if 'TEMPLATE_DIR' in os.environ: | |
templates_folder = os.environ['TEMPLATE_DIR'] | |
else: | |
templates_folder = r"C:\Users\USER\Downloads\templates" | |
delete_output = 'SAVE_OUTPUT' not in os.environ | |
data_dir = templates_folder | |
# Load an image in an instance of Image | |
with Image.load(os.path.join(data_dir, "template.jpg")) as image: | |
# Cast the image to RasterCachedImage and check if image is cached | |
raster_cached_image = aspycore.as_of(image, RasterCachedImage) | |
if not raster_cached_image.is_cached: | |
# Cache image if not already cached | |
raster_cached_image.cache_data() | |
# Convert the image in grayscale and save the resultant image | |
raster_cached_image.grayscale() | |
raster_cached_image.save(os.path.join(data_dir, "result.jpg")) | |
if delete_output: | |
os.remove(os.path.join(data_dir, "result.jpg")) |
Convert GIF Image Layers To TIFF Image
Sometimes it is needed to extract and convert layers of a GIF Image into another raster image format to meet an application need. Aspose.Imaging API support the feature of extracting and converting layers of a GIF Image into another raster image formats. Firstly, we will create instance of image and load GIF image from the local disk, then we will get the total count of layers in the source image using Length property of GifFrameBlock class and iterate through the array of blocks. Now we will check if the block is NULL then ignore it else convert the block to TIFF image. The following code snippet shows you how to convert GIF image layers to TIFF image.
import aspose.pycore as aspycore | |
from aspose.imaging import Image | |
from aspose.imaging.fileformats.gif import GifImage | |
from aspose.imaging.fileformats.gif.blocks import GifFrameBlock | |
from aspose.imaging.fileformats.tiff.enums import TiffExpectedFormat | |
from aspose.imaging.imageoptions import TiffOptions | |
import os | |
if 'TEMPLATE_DIR' in os.environ: | |
templates_folder = os.environ['TEMPLATE_DIR'] | |
else: | |
templates_folder = r"C:\Users\USER\Downloads\templates" | |
delete_output = 'SAVE_OUTPUT' not in os.environ | |
data_dir = templates_folder | |
# Load a GIF image and Convert the image to GIF image | |
obj_image = Image.load(os.path.join(data_dir, "template.gif")) | |
with aspycore.as_of(obj_image, GifImage) as gif: | |
index = 1 | |
# Iterate through array of blocks in the GIF image | |
for block in gif.blocks: | |
# Check if is not GifFrameBlock then ignore it | |
if not aspycore.is_assignable(block, GifFrameBlock): | |
continue | |
# Convert block to GifFrameBlock class instance | |
gif_block = aspycore.as_of(block, GifFrameBlock) | |
# Create an instance of TIFF Option class and Save the GIFF block as TIFF image | |
obj_tiff = TiffOptions(TiffExpectedFormat.DEFAULT) | |
gif_block.save(os.path.join(data_dir, f"result_{index}.tiff"), obj_tiff) | |
index += 1 | |
if delete_output: | |
for i in range(1, index): | |
os.remove(os.path.join(data_dir, f"result_{i}.tiff")) |
Converting SVG to Raster Format
See :
Converting Raster Image to PDF
See :
Converting Raster Image to Svg
See
Converting RGB color system to CMYK for Tiff file Format
Using Aspose.Imaging for Python via .NET, developers can convert RGB color system file to CMYK tiff format. This article shows how to export/convert RGB color system file to CMYK tiff format with Aspose.Imaging. Using Aspose.Imaging for Python via .NET you can load image of any format and than you can set various properties using TiffOptions class and save the image. The following code snippet shows you how to achieve this feature.
from aspose.imaging import Image | |
from aspose.imaging.fileformats.tiff.enums import TiffExpectedFormat | |
from aspose.imaging.imageoptions import TiffOptions | |
import os | |
if 'TEMPLATE_DIR' in os.environ: | |
templates_folder = os.environ['TEMPLATE_DIR'] | |
else: | |
templates_folder = r"C:\Users\USER\Downloads\templates" | |
delete_output = 'SAVE_OUTPUT' not in os.environ | |
data_dir = templates_folder | |
options = TiffOptions(TiffExpectedFormat.TIFF_LZW_CMYK) | |
with Image.load(os.path.join(data_dir, "template.tiff")) as image: | |
image.save(os.path.join(data_dir, "result.tiff"), options) | |
if delete_output: | |
os.remove(os.path.join(data_dir, "result.tiff")) |
Working with animation
See
Converting Open document graphics
See
Converting Corel Draw images
See Convert CDR
Converting webp images
Converting eps images
Converting cmx images
Converting dicom images
Exporting Images
Along with a rich set of image processing routines, Aspose.Imaging provides specialized classes to convert images to other formats. Using this library, image format conversion is as simple as changing the file extension to desired format in the Image class save method and by specifying the appropriate ImageOptions values. Below are some specialized classes for this purpose in ImageOptions namespace.
It is easy to export images with Aspose.Imaging for Python via .NET API. All you need is an object of the appropriate class from ImageOptions namespace. By using these classes, you can easily export any image created, edited or simply loaded with Aspose.Imaging for Python via .NET to any supported format. Below is an example that demonstrates this simple procedure. In the example, a GIF image is loaded by passing the file path as a parameter to the load method. It is then exported to various image formats using the save method. The examples here show how to load a GIF and save it to BMP, JPEG, PNG and finally TIFF using Aspose.Imaging for Python via .NET with Python.
import aspose.pycore as aspycore | |
from aspose.imaging import Image | |
from aspose.imaging.fileformats.tiff.enums import TiffExpectedFormat | |
from aspose.imaging.imageoptions import BmpOptions, JpegOptions, PngOptions, TiffOptions | |
import os | |
if 'TEMPLATE_DIR' in os.environ: | |
templates_folder = os.environ['TEMPLATE_DIR'] | |
else: | |
templates_folder = r"C:\Users\USER\Downloads\templates" | |
delete_output = 'SAVE_OUTPUT' not in os.environ | |
data_dir = templates_folder | |
# Load an existing image (of type Gif) in an instance of the Image class | |
with Image.load(os.path.join(data_dir, "template.gif")) as image: | |
# Export to BMP, JPEG, PNG and TIFF file format using the default options | |
image.save(os.path.join(data_dir, "result.bmp"), BmpOptions()) | |
image.save(os.path.join(data_dir, "result.jpeg"), JpegOptions()) | |
image.save(os.path.join(data_dir, "result.png"), PngOptions()) | |
image.save(os.path.join(data_dir, "result.tiff"), TiffOptions(TiffExpectedFormat.DEFAULT)) | |
if delete_output: | |
os.remove(os.path.join(data_dir, "result.bmp")) | |
os.remove(os.path.join(data_dir, "result.jpeg")) | |
os.remove(os.path.join(data_dir, "result.png")) | |
os.remove(os.path.join(data_dir, "result.tiff")) |
Convert compressed vector formats
Aspose.Imaging supports next compressed vector formats: Emz(compressed emf), Wmz(compressed wmf), Svgz(compressed svg). Supported read of these formats and export to other formats.
Combining Images
This example uses Graphics class and shows how to combine two or more images into a single complete image.To demonstrate the operation, the example creates a new Image canvas in JPEG format and draw images on the canvas surface using draw_image method exposed by Graphics class. Using Graphics class two or more images can be combine in such a way that the resultant image will look as a complete image with no space between the image parts and no pages. The canvas size must be equal to the size of resultant image. Following is the code demonstration that shows how to use draw_image method of the Graphics class to combine images in a single image.
import aspose.pycore as aspycore | |
from aspose.imaging import Image, Graphics, Color | |
from aspose.imaging.imageoptions import JpegOptions | |
from aspose.imaging.sources import FileCreateSource | |
import os | |
if 'TEMPLATE_DIR' in os.environ: | |
templates_folder = os.environ['TEMPLATE_DIR'] | |
else: | |
templates_folder = r"C:\Users\USER\Downloads\templates" | |
delete_output = 'SAVE_OUTPUT' not in os.environ | |
data_dir = templates_folder | |
# Create an instance of JpegOptions and set its various properties | |
image_options = JpegOptions() | |
# Create an instance of FileCreateSource and assign it to Source property | |
image_options.source = FileCreateSource(os.path.join(data_dir, "result.jpg"), False) | |
# Create an instance of Image and define canvas size | |
with Image.create(image_options, 600, 600) as image: | |
# Create and initialize an instance of Graphics, Clear the image surface with white color and Draw Image | |
graphics = Graphics(image) | |
graphics.clear(Color.white) | |
graphics.draw_image(Image.load(os.path.join(data_dir, "template.bmp")), 0, 0, 600, 300) | |
graphics.draw_image(Image.load(os.path.join(data_dir, "template.jpg")), 0, 300, 600, 300) | |
image.save() | |
if delete_output: | |
os.remove(os.path.join(data_dir, "result.jpg")) |
Expand and Crop Images
Aspose.Imaging API allows you to expand or crop an image during image conversion process. Developer needs to create a rectangle with X and Y coordinates and specify the width and height of the rectangle box. The X,Y and Width, Height of rectangle will depict the expansion or cropping of the loaded image. If it is required to expand or crop the image during image conversion, perform the following steps:
- Create an instance of RasterImage class and load the existing image.
- Create an Instance of ImageOption class.
- Create an instance of Rectangle class and initialize the X,Y and Width, Height of the rectangle
- Call Save method of the RasterImage class while passing output file name, image options and the rectangle object as parameters.
import aspose.pycore as aspycore | |
from aspose.imaging import RasterImage, Image, Rectangle | |
from aspose.imaging.fileformats.tiff.enums import * | |
from aspose.imaging.imageoptions import * | |
from aspose.imaging.sources import * | |
import os | |
if 'TEMPLATE_DIR' in os.environ: | |
templates_folder = os.environ['TEMPLATE_DIR'] | |
else: | |
templates_folder = r"C:\Users\USER\Downloads\templates" | |
delete_output = 'SAVE_OUTPUT' not in os.environ | |
data_dir = templates_folder | |
# Load an image in an instance of Image and Setting for image data to be cashed | |
with aspycore.as_of(Image.load(os.path.join(data_dir, "template.jpg")), RasterImage) as raster_image: | |
raster_image.cache_data() | |
# Create an instance of Rectangle class and define x, y and width, height of the rectangle, and save output image | |
dest_rect = Rectangle() | |
dest_rect.x = -200 | |
dest_rect.y = -200 | |
dest_rect.width = 300 | |
dest_rect.height = 300 | |
raster_image.save(os.path.join(data_dir, "result.jpg"), JpegOptions(), dest_rect) | |
if delete_output: | |
os.remove(os.path.join(data_dir, "result.jpg")) |
Read and Write XMP Data To Images
XMP (Extensible Metadata Platform) is an ISO standard. XMP standardizes a data model, a serialization format and core properties for the definition and processing of extensible metadata. It also provides guidelines for embedding XMP information into popular image such as JPEG, without breaking their readability by applications that do not support XMP. Using Aspose.Imaging for Python via .NET API developers can read or write XMP metadata to images. This article demonstrates how XMP metadata can be read from image and write XMP metadata to images.
Create XMP Metadata, Write It And Read From File
The release of Aspose.Imaging 3.3.0 contains the Xmp namespace. With the help of Xmp namespace developer can create XMP metadata object and write it to an image. The following code snippet shows you how to use the XmpHeaderPi, XmpTrailerPi, XmpMeta, XmpPacketWrapper, PhotoshopPackage and DublinCorePackage packages contained in Xmp namespace.
import aspose.pycore as aspycore | |
from aspose.imaging import * | |
from aspose.imaging.fileformats.tiff import * | |
from aspose.imaging.fileformats.tiff.enums import TiffExpectedFormat, TiffPhotometrics | |
from aspose.imaging.imageoptions import TiffOptions | |
from aspose.imaging.xmp import * | |
from aspose.imaging.xmp.schemas.dublincore import * | |
from aspose.imaging.xmp.schemas.photoshop import * | |
from aspose.imaging.extensions import StreamExtensions | |
import os | |
import uuid | |
from datetime import datetime | |
if 'TEMPLATE_DIR' in os.environ: | |
templates_folder = os.environ['TEMPLATE_DIR'] | |
else: | |
templates_folder = r"C:\Users\USER\Downloads\templates" | |
delete_output = 'SAVE_OUTPUT' not in os.environ | |
data_dir = templates_folder | |
# Specify the size of image by defining a Rectangle | |
rect = Rectangle(0, 0, 100, 200) | |
tiff_options = TiffOptions(TiffExpectedFormat.TIFF_JPEG_RGB) | |
tiff_options.photometric = TiffPhotometrics.MIN_IS_BLACK | |
tiff_options.bits_per_sample = [8] | |
# Create the brand new image just for sample purposes | |
with TiffImage(TiffFrame(tiff_options, rect.width, rect.height)) as image: | |
# Create an instance of XMP-Header | |
xmp_header = XmpHeaderPi(str(uuid.uuid4())) | |
# Create an instance of Xmp-TrailerPi, XMPmeta class to set different attributes | |
xmp_trailer = XmpTrailerPi(True) | |
xmp_meta = XmpMeta() | |
xmp_meta.add_attribute("Author", "Mr Smith") | |
xmp_meta.add_attribute("Description", "The fake metadata value") | |
# Create an instance of XmpPacketWrapper that contains all metadata | |
xmp_data = XmpPacketWrapper(xmp_header, xmp_trailer, xmp_meta) | |
# Create an instance of Photoshop package and set Photoshop attributes | |
photoshop_package = PhotoshopPackage() | |
photoshop_package.set_city("London") | |
photoshop_package.set_country("England") | |
photoshop_package.set_color_mode(ColorMode.RGB) | |
photoshop_package.set_created_date(datetime.now()) | |
# Add Photoshop package into XMP metadata | |
xmp_data.add_package(photoshop_package) | |
# Create an instance of DublinCore package and set dublinCore attributes | |
dublin_core_package = DublinCorePackage() | |
dublin_core_package.set_author("Charles Bukowski") | |
dublin_core_package.set_title("Confessions of a Man Insane Enough to Live With the Beasts") | |
dublin_core_package.add_value("dc:movie", "Barfly") | |
# Add dublinCore Package into XMP metadata | |
xmp_data.add_package(dublin_core_package) | |
with StreamExtensions.create_memory_stream() as ms: | |
# Update XMP metadata into image and Save image on the disk or in memory stream | |
image.xmp_data = xmp_data | |
image.save(ms) | |
ms.seek(0) | |
# Load the image from memory stream or from disk to read/get the metadata | |
with aspycore.as_of(Image.load(ms), TiffImage) as img: | |
# Getting the XMP metadata | |
img_xmp_data = img.xmp_data | |
for package in img_xmp_data.packages: | |
# do something | |
print(package) | |
pass |
Export Images in Multi Threaded Environment
Aspose.Imaging for Python via .NET now supports converting images in multi threaded environment. Aspose.Imaging for Python via .NET ensure the optimized performance of operations during execution of code in multi-threaded environment. All imaging option classes (e.g. BmpOptions, TiffOptions, JpegOptions, etc.) in the Aspose.Imaging for Python via .NET now implement enter and exit methods and could be used with with operator. Therefore it is a must that developer properly dispose off the imaging options class object in case source property is set. Following code snippet demonstrates the said functionality.
import aspose.pycore as aspycore | |
from aspose.imaging import RasterImage, Image, Color, Rectangle | |
from aspose.imaging.imageoptions import BmpOptions | |
from aspose.imaging.sources import FileOpenSource | |
import os | |
import shutil | |
if 'TEMPLATE_DIR' in os.environ: | |
templates_folder = os.environ['TEMPLATE_DIR'] | |
else: | |
templates_folder = r"C:\Users\USER\Downloads\templates" | |
delete_output = 'SAVE_OUTPUT' not in os.environ | |
data_dir = templates_folder | |
image_data_path = "" | |
try: | |
# Path & name of existing image. | |
image_data_path = os.path.join(data_dir, "template.bmp") | |
shutil.copy2(image_data_path, image_data_path + ".copy.bmp") | |
image_data_path = image_data_path + ".copy.bmp" | |
# Create an instance of BMP image option class. | |
with BmpOptions() as bmp_options: | |
bmp_options.bits_per_pixel = 32 | |
# Set the source property of the imaging option class object. | |
bmp_options.source = FileOpenSource(image_data_path) | |
# DO PROCESSING. | |
# Following is the sample processing on the image. Un - comment to use it. | |
with aspycore.as_of(Image.create(bmp_options, 10, 10), RasterImage) as image: | |
pixels = [] | |
for i in range(4): | |
pixels.append(Color.from_argb(40, 30, 20, 10)) | |
image.save_pixels(Rectangle(0, 0, 2, 2), pixels) | |
image.save() | |
finally: | |
# Delete the file. This statement is in the final block because in any case this statement should execute to make it sure that resource is properly disposed off. | |
if delete_output: | |
os.remove(image_data_path) |