BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Basic Image Operations - pixel access

OpenCV_Logo.png




Bookmark and Share





bogotobogo.com site search:

Image Loading

To load an image, we can use imread() function. It loads an image from the specified file and returns it. Actually, it reads an image as an array of RGB values. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ). Even if the image path is wrong, it won't throw any error, but print image will give us None.

Here are the file formats that are currently supported:

  1. Windows bitmaps - *.bmp, *.dib
  2. JPEG files - *.jpeg, *.jpg, *.jpe
  3. JPEG 2000 files - *.jp2
  4. Portable Network Graphics - *.png
  5. Portable image format - *.pbm, *.pgm, *.ppm
  6. Sun rasters - *.sr, *.ras
  7. TIFF files - *.tiff, *.tif

CloudyGoldenGate.jpg:

CloudyGoldenGate.jpg


CloudyGoldenGate_grayscale.jpg:

CloudyGoldenGate_grayscale.jpg

Here is a simple python code for image loading:

import cv2
import numpy as np
img = cv2.imread('images/CloudyGoldenGate.jpg')

The syntax for the imread() looks like this:

cv2.imread(filename[, flags]) 

The flags is to specify the color type of a loaded image:

  1. CV_LOAD_IMAGE_ANYDEPTH - If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
  2. CV_LOAD_IMAGE_COLOR - If set, always convert image to the color one.
  3. CV_LOAD_IMAGE_GRAYSCALE - If set, always convert image to the grayscale one.
  4. >0 Return a 3-channel color image.
  5. =0 Return a grayscale image.
  6. <0 Return the loaded image as is (with alpha channel).


bogotobogo.com site search:


Image Properties - shape, size, and dtype

TriColor.png

Image properties include number of rows, columns and channels, type of image data, number of pixels etc.

Shape of image is accessed by img.shape. It returns a tuple of number of rows, columns and channels. If image is grayscale, tuple returned contains only number of rows and columns. So it is a good method to check if loaded image is grayscale or color image:

import cv2
import numpy as np

img_file = 'images/TriColor.png'
img = cv2.imread(img_file, cv2.IMREAD_COLOR)           # rgb
alpha_img = cv2.imread(img_file, cv2.IMREAD_UNCHANGED) # rgba
gray_img = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)  # grayscale

print type(img)
print 'RGB shape: ', img.shape        # Rows, cols, channels
print 'ARGB shape:', alpha_img.shape
print 'Gray shape:', gray_img.shape
print 'img.dtype: ', img.dtype
print 'img.size: ', img.size

Output:

<type 'numpy.ndarray'>
RGB shape:  (240, 240, 3)
ARGB shape: (240, 240, 4)
Gray shape: (240, 240)
img.dtype:  uint8
img.size:  172800
  1. img.dtype (usually, dtype=np.uint8) is very important while debugging because a large number of errors in OpenCV-Python code is caused by invalid datatype.
  2. If image is grayscale, tuple returned does not contain any channels.
  3. The number of channels for ARGB = 4.



Pixel Accessing

We can access a pixel value by its row and column coordinates. For BGR image, it returns an array of Blue, Green, Red values. For grayscale image, corresponding intensity is returned.

We get BGR value from the color image:

img[45, 90] = [200 106   5]       # mostly blue
img[173, 25] = [  0 111   0]      # green
img[145, 208] =  [  0   0 177]    # red

We can also access the alpha value (transparent = 0, opaque = 255) and grayscale value (intensity) as well.

alpha_img[173, 25] = [  0 111   0 255]    # opaque
gray_img[173, 25] =  87                   # intensity for grayscale

If we specify what we want to get. Here we specified 5x5 pixels:

alpha_img[170:175, 25:30, 0] =  [[0 0 0 0 0]             # blue
 [1 0 0 0 0]
 [2 0 0 0 0]
 [0 1 0 0 0]
 [0 2 0 0 0]]
alpha_img[170:175, 25:30, 1] =  [[137 150 161 170 178]   # green
 [130 143 155 165 173]
 [122 136 148 159 168]
 [111 128 140 152 162]
 [ 98 120 132 145 155]]
alpha_img[170:175, 25:30, 2] =  [[0 0 0 0 0]             # red
 [1 0 0 0 0]
 [2 0 0 0 0]
 [0 1 0 0 0]
 [0 2 0 0 0]]
alpha_img[170:175, 25:30, 3] =  [[255 255 255 255 255]   # alpha
 [255 255 255 255 255]
 [255 255 255 255 255]
 [255 255 255 255 255]
 [255 255 255 255 255]]
gray_img[170:175, 25:30] =  [[107 117 126 133 140]       # intensity
 [102 111 120 129 135]
 [ 95 106 116 124 131]
 [ 87  99 109 119 127]
 [ 76  93 103 114 120]]






Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong








OpenCV 3 image and video processing with Python



OpenCV 3 with Python

Image - OpenCV BGR : Matplotlib RGB

Basic image operations - pixel access

iPython - Signal Processing with NumPy

Signal Processing with NumPy I - FFT and DFT for sine, square waves, unitpulse, and random signal

Signal Processing with NumPy II - Image Fourier Transform : FFT & DFT

Inverse Fourier Transform of an Image with low pass filter: cv2.idft()

Image Histogram

Video Capture and Switching colorspaces - RGB / HSV

Adaptive Thresholding - Otsu's clustering-based image thresholding

Edge Detection - Sobel and Laplacian Kernels

Canny Edge Detection

Hough Transform - Circles

Watershed Algorithm : Marker-based Segmentation I

Watershed Algorithm : Marker-based Segmentation II

Image noise reduction : Non-local Means denoising algorithm

Image object detection : Face detection using Haar Cascade Classifiers

Image segmentation - Foreground extraction Grabcut algorithm based on graph cuts

Image Reconstruction - Inpainting (Interpolation) - Fast Marching Methods

Video : Mean shift object tracking

Machine Learning : Clustering - K-Means clustering I

Machine Learning : Clustering - K-Means clustering II

Machine Learning : Classification - k-nearest neighbors (k-NN) algorithm

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master