python logo


Tag: image

Image data and operations

OpenCV (cv2) can be used to extract data from images and do operations on them. We demonstrate some examples of that below:

Related courses:

Image properties
We can extract the width, height and color depth using the code below:

import cv2
import numpy as np

# read image into matrix.
m = cv2.imread("python.png")

# get image properties.
h,w,bpp = np.shape(m)

# print image properties.
print "width: " + str(w)
print "height: " + str(h)
print "bpp: " + str(bpp)

Access pixel data
We can access the pixel data of an image directly using the matrix, example:

import cv2
import numpy as np

# read image into matrix.
m = cv2.imread("python.png")

# get image properties.
h,w,bpp = np.shape(m)

# print pixel value
y = 1
x = 1
print m[y][x]

To iterate over all pixels in the image you can use:

import cv2
import numpy as np

# read image into matrix.
m = cv2.imread("python.png")

# get image properties.
h,w,bpp = np.shape(m)

# iterate over the entire image.
for py in range(0,h):
for px in range(0,w):
print m[py][px]

Image manipulation
You can modify the pixels and pixel channels (r,g,b) directly. In the example below we remove one color channel:

import cv2
import numpy as np

# read image into matrix.
m = cv2.imread("python.png")

# get image properties.
h,w,bpp = np.shape(m)

# iterate over the entire image.
for py in range(0,h):
for px in range(0,w):
m[py][px][0] = 0

# display image
cv2.imshow('matrix', m)
cv2.waitKey(0)

To change the entire image, you’ll have to change all channels:   m[py][px][0], m[py][px][1], m[py][px][2].

Save image
You can save a modified image to the disk using:

cv2.imwrite('filename.png',m)

Download Computer Vision Examples + Course

QT4 Pixmaps (Images)

In this article we will demonstrate how to load and display images in an PyQT window. We can display images in a PyQT window using the Pixmap widget.

PyQt4-load-image An image loaded in a PyQt4 window.

Related course:

Introduction


The constructor of Pixmap takes the image path as parameter:

pixmap = QPixmap(os.getcwd() + '/logo.png')

This image needs to be in the same directory as your program. The QPixmap widget supports png and jpeg.  Example code below.

PyQT load image in Pixmap


We create a standard QWidget as we have done before. Then we add the QPixmap widget inside which will load the image. The Pixmap is attached to a label which is drawn to the screen.

import os
import sys
from PyQt4.QtGui import *

# Create window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle("PyQT4 Pixmap @ pythonspot.com ")

# Create widget
label = QLabel(w)
pixmap = QPixmap(os.getcwd() + '/logo.png')
label.setPixmap(pixmap)
w.resize(pixmap.width(),pixmap.height())

# Draw window
w.show()
app.exec_()

Download PyQT Code (Bulk Collection)

Result:

pyqt Pixmap pyqt Pixmap