Pixel Reader – Project using Raspberry Pi

by Mar 25, 2020Raspberry Pi projects

Starting to get interested in image processing and its applications? This project is ideal as a first step to understand the fundamentals of any image- pixels. Pixels are small boxes of color that constitute any image. We throw around the word ‘pixels’ a lot in our everyday life, like when describing your mobile phone camera to a friend. But, understanding what they actually are is important in image processing.

The aim of this project is to build a program that will allow us to view the color components (Red, Green, Blue) in each pixel. We capture the image using the Raspberry Pi camera, and then pick the desired area. This project is the first step in larger projects like image matching, forgery detection and deep learning.

Hardware Requirements:

  1. Raspberry Pi (I used, model 3 B +)
  2. Camera module
  3. Power cable
  4. Monitor
  5. HDMI connector
  6. USB or Bluetooth mouse
  7. USB or Bluetooth keyboard

Setup:

  1. Connect the Raspberry Pi camera module (for any help on that, check out our article on that https://iot4beginners.com/how-to-capture-image-and-video-in-raspberry-pi/ ).
  2. Use the HDMI cable to connect your Raspberry Pi to a display
  3. Connect your mouse and keyboard as well (through USB or Bluetooth)
  4. Make sure to install NumPy and OpenCV library on your Raspberry Pi before you start
initial setup

What is OpenCV?

OpenCV is an open-source library for computer vision, machine learning, and image processing. It is especially useful in real-time systems which makes it a desirable tool to learn and implement. When it integrated with NumPy, Python can process OpenCV for analysis. This is why when coding with OpenCV in Python we also import NumPy, which is a library that is used with Python to perform matrix computations, and linear algebra among other complex mathematical functions

Code:

import numpy as np 
import cv2
import picamera
import time

#take a realtime image
with picamera.PiCamera() as camera:
	camera.resolution = (512,512)
	camera.start_preview()
	time.sleep(5)
	camera.capture("/home/pi/Desktop/microscope/rtimg.jpg")

#make a copy of the original image
img = cv2.imread('rtimg.jpg', cv2.IMREAD_UNCHANGED)
cv2.imwrite('rtimg2.jpg', img)
while True:
	#read image
	im = cv2.imread('rtimg2.jpg',cv2.IMREAD_UNCHANGED)

	#select ROI
	r = cv2.selectROI(im)

	#crop
	imCrop = im[int(r[1]):int(r[1]+r[3]),int(r[0]):int(r[0]+r[2])]
#zoom
	scale_percent = 400
	#scale_percent = int(input ("enter : "))
	width = int(imCrop.shape[1] *scale_percent / 100)
	height = int(imCrop.shape[0] *scale_percent / 100)
	dim =(width,height)
	imZoom = cv2.resize(imCrop,dim,interpolation = cv2.INTER_AREA)
	
	#save cropped
	cv2.imwrite('rtimg2.jpg', imZoom)
	
	#ask for continuation
	def click_and_crop(event, x, y, flags, param):
		if event == cv2.EVENT_LBUTTONDOWN:
			refPt = [(x, y)]
			cropping = True
	
		elif event == cv2.EVENT_LBUTTONUP:
			refPt.append((x, y))
			cropping = False
	 
			cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
			cv2.imshow("image", image)
	
#show zoomed image
img = cv2.imread('rtimg2.jpg'.jpg')
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Explanation for the code:

To write the code for this project, we begin by importing the libraries needed for running the code.

import numpy as np 
import cv2
import picamera
import time

Now take a picture using the Raspberry Pi camera, the code below will give you 5 seconds time to position your camera while showing you a preview of the image on the screen. Also we make a temporary copy of the image in order to retain the original image.

#take a realtime image 

with picamera.PiCamera() as camera:
	camera.resolution = (512,512)
	camera.start_preview()
	time.sleep(5)
	camera.capture("/home/pi/Desktop/rtimg.jpg") #insert name and desired location

#make a copy of the original image
img = cv2.imread('rtimg.jpg', cv2.IMREAD_UNCHANGED)
cv2.imwrite('rtimg2.jpg', img)

We now write a code to allow the user to use a rectangular ROI to select the part of image they want to zoom into.

while True:
	#read image
	im = cv2.imread('rtimg2.jpg',cv2.IMREAD_UNCHANGED)

	#select ROI 
	r = cv2.selectROI(im)

	#crop
	imCrop = im[int(r[1]):int(r[1]+r[3]),int(r[0]):int(r[0]+r[2])]
	
	#zoom parameters
	scale_percent = 400  #feel free to vary this parameter
	width = int(imCrop.shape[1] *scale_percent / 100)
	height = int(imCrop.shape[0] *scale_percent / 100)
	dim =(width,height)
	imZoom = cv2.resize(imCrop,dim,interpolation = cv2.INTER_AREA)
	
	#save cropped
	cv2.imwrite('rtimg2.jpg', imZoom)

The program must reiterate the selecting process till the user has selected only the area desired to be zoomed into, thus we define a mouse click event to select again.

	#ask for continuation
	def click_and_crop(event, x, y, flags, param):
		if event == cv2.EVENT_LBUTTONDOWN:
			refPt = [(x, y)]
			cropping = True
	
		elif event == cv2.EVENT_LBUTTONUP:
			refPt.append((x, y))
			cropping = False
	 
			cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
			cv2.imshow("image", image)
	

We now finish the code by displaying the image on which we can scroll using the mouse to view the component values of each pixel.

#show zoomed image
img = cv2.imread('rtimg2.jpg'.jpg')
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Outputs:

Capture image using pi camera and select region of interest
Select ROI again to zoom in to desired area
Individual values (R,G,B) can be viewed for each pixel on scrolling further using your mouse

 This project not only is useful as a baseline for larger deep learning projects, but is also useful as a practical approach to understanding pixels. Viewing things with our own eyes makes comprehending it much easier. And even though pixels in images are much smaller than what meets the eye, through this project it makes it easy to see what makes the big picture so beautiful.

Creating a multiplication Skill in Alexa using python

Written By Jyotsna Rajaraman

Hi! I'm Jyotsna, an electronics and communication undergrad who likes reading, writing, talking and learning. So when it comes to teaching, all my favorite things come together! I hope my articles have helped and taught you something. 🙂

RELATED POSTS

Magic Wand using Raspberry Pi and OpenCV

Magic Wand using Raspberry Pi and OpenCV

What if I could do things with a swing of a wand? Practically impossible but with technology maybe not. In this tutorial, we will use a raspberry pi and OpenCV to try and recreate something similar to a wand. It will perform specific functions when it recognizes...

IBM Watson IoT Platform with Raspberry Pi

IBM Watson IoT Platform with Raspberry Pi

IBM Watson is one of the leading cloud computing platforms there is. It has almost all the features one could expect from a modern-day cloud platform, from machine learning support to IoT, even till edge computing. In this tutorial, we will use raspberry pi and an...

Home Automation With Telegram and Raspberry Pi

Home Automation With Telegram and Raspberry Pi

In this Article we will see how we can use Telegram for Home Automation. Telegram is an extremely popular multi-platform messaging service. Just like any other messaging platform, it is used to send messages and exchange photos, videos, stickers, audio, and files of...

Home Automation System with Raspberry Pi and Flask

Home Automation systems are becoming increasingly popular for the level of convenience they offer. Imagine sitting on your couch and turning on/off lights or fans in the room without having to get up. You could also control blinds or even door locks. This project is a...

Smart Alarm Clock with Raspberry Pi

Smart Alarm Clock with Raspberry Pi

Smart Alarms are very common today yet the good ones expensive. What if you wanted to make a smart alarm clock on your own using as little hardware and cost as possible? You may ask isn't the RPI costly, yes it is but, the only purpose of using an RPI is easy to net...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....