Image and Its Properties 49
in all major operating system like Windows, Linux, UNIX, Mac,
etc. It can read all DICOM formats and can store the data in
various common file formats and also as movies. The plugins allow
various image processing operations. Since the plugins can be
easily added, the complexity of the image processing operation
is limited only by the user’s knowledge of Java. Since ImageJ
is a popular image processing software, a brief introduction is
presented in Appendix C, “Introduction to ImageJ.”
3.4 Data Structures for Image Analysis
Image data is generally stored as a mathematical matrix. So in
general, a 2D image of size 1024-by-1024 is stored in a matrix of the
same size. Similarly, a 3D image is stored in a 3D matrix. In numpy, a
mathematical matrix is called a numpy array. As we will be discussing
in the subsequent chapters, the images are read and stored as a numpy
array and then processed using either functions in a Python module or
user-defined functions.
Since Python is a dynamically typed language (i.e., no defining data
type), it will determine the data type and size of the image at run time
and store appropriately.
3.5 Reading, Writing and Displaying Images
3.5.1 Reading Images
After a lot of research, we decided to use Python’s computer vision
module, OpenCV [Ope20a] for reading and writing images, the PIL
module’s Image for reading images, and Matplotlib’s pyplot to display
images.
50 Image Processing and Acquisition using Python
OpenCV is imported as cv2. We use imread function to read an
image, which returns an ndarray. The cv2.imread supports the following
file formats:
• Windows bitmaps: bmp, dib
• JPEG files: jpeg, jpg, jpe
• JPEG 2000 files: jp2
• Portable Network Graphics: png
• Portable image format: pbm, pgm, ppm
• TIFF files: tiff, tif
Below is the cv2’s code snippet for reading images.
import cv2
# Reading image and converting it into an ndarray
img = cv2.imread('Picture1.png')
# Converting img to grayscale
img_grayscale = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
We import cv2 and use the cv2.imread function to read the image
as an ndarray. To convert a color image to grayscale, we use the
function cvtColor whose first argument is the ndarray of an image
and the second argument is cv2.COLOR BGR2GRAY. This argument,
cv2.COLOR BGR2GRAY, converts an RGB image, which is a three-
channel ndarray to grayscale, which is a single-channel ndarray using
the following formula:
y = 0.299 ∗ R + 0.587 ∗ G + 0.114 ∗ B (3.1)
Another way to read images would be using PIL module’s Image
class. Below is the code snippet for reading images using PIL’s Image.