Shape detector using python | image processing

Lett us see how to detect shapes in the given image using python coding.

Description:

Given an image you have to estimate the geometric shapes and their respective numbers in the
image. The image will have any number of shapes. The objects can be of any color. You can
assume there will be a contrast between the color of the object and the background.

Input format:

<program> <input image>
Example :
<program> input.jpg

Output format:

<number_of_vertices_for _the_shape> <
number_of_such_shapes>

Program:

import numpy as np
import sys
import cv2

ab = [0] * 20
j = 20

# load the image
image = cv2.imread(str(sys.argv[1]))
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray,(5,5),0)
gray = cv2.bilateralFilter(gray,9,75,75)
##cv2.imshow("org", gray)

edged = cv2.Canny(gray,75,300)
##cv2.imshow("edge",edged)

# find the contours in the mask
(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)

# loop over the contours
for c in cnts:
        # draw the contour and show it
        area = cv2.contourArea(c)
        if area < 10:
                continue
        cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
        peri = cv2.arcLength(c,True)
        approx = cv2.approxPolyDP(c,0.02*peri,True)
        h = len(approx)
        ab[h] = ab[h]+1

#print the shapes and their numbers
for k in range(20) :
        if ab[k] == 0:
             continue
        print "%d - %d" %(k,ab[k])
cv2.destroyAllWindows()

#Show the detected shapes
#cv2.imshow("Image", image)
#cv2.waitKey(0)
#cv2.destroyAllWindows()

It works fine with the below images




Cheers!!!!
-> Let Us Embed <-

Counting/Detecting Number of rectangles in the given image in image processing using python coding | Rect O'Mania

Let us see Rect O'Mania which means counting of number of rectangles in the given image using python coding.

Question Description

A binary image is one in which each pixel is either white or black. The input in this problem is a
binary image which contains a number of nonoverlapping
white rectangles in a black
background. The rectangles can be in any orientation. You are expected to find the centre of the
rectangle(s) and also find the angle of rotation of each rectangle with respect to the horizontal.
Note: Measure the angle between the axis parallel to the longer edge of the rectangle passing
through centre and measure the angle in anticlockwise
direction from the horizontal.

Input format

<program> <input image>
Example :
<program> input.jpg

Output format

N
X1, Y1, D1
X2, Y2, D2
.
.
.
Xn, Yn, Dn
Where
N is the number of rectangles detected
Xi is the X coordinate of the i th rectangle
Yi is the Y coordinate of the i th rectangle
Di is the Angle ( See Note Carefully ) in degrees (0 <= D < 180)
N, Xi, Yi, Di are integers. The ordering must be in terms of size ( Largest >
Smallest )
Answers are accepted with an error or +1/1
in the coordinates (i.e., X1,
X+1, X ) and +2/2
in
the angle.

Python Program

import numpy as np
import cv2
import math
import sys

flag = 0

img = cv2.imread(str(sys.argv[1]))
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret1,thresh1 = cv2.threshold(imgray,127,255,cv2.THRESH_BINARY)
ret2,thresh2 = cv2.threshold(imgray,127,255,cv2.THRESH_BINARY_INV)
contoursb1, hierarchyb1 = cv2.findContours(thresh1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contoursb2, hierarchyb2 = cv2.findContours(thresh2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

contoursb = contoursb1
if len(contoursb2)>len(contoursb1):
    contoursb = contoursb2

contoursb = sorted(contoursb, key = cv2.contourArea, reverse = True)
print len(contoursb)
 
for i in range(len(contoursb)):
    cntb=contoursb[i]          
    M=cv2.moments(cntb) #center of bot
 
    if M['m00']!=0 :          
        xb=int(M['m10']/M['m00'])
        yb=int(M['m01']/M['m00'])
        centrb=(xb,yb)
        cv2.circle(img,(xb,yb),1,(255,0,0),2)
        area = cv2.contourArea(cntb)
        rect = cv2.minAreaRect(cntb)
        box = cv2.cv.BoxPoints(rect)
        p1 = box[0]
        p2 = box[1]
        p3 = box[3]
        n1 = math.sqrt(((p1[0]-p2[0])*(p1[0]-p2[0]))+((p1[1]-p2[1])*(p1[1]-p2[1])))
        n2 = math.sqrt(((p1[0]-p3[0])*(p1[0]-p3[0]))+((p1[1]-p3[1])*(p1[1]-p3[1])))

        if n1<n2:
            x1 = int((p1[0]+p2[0])/2)
            y1 = int((p1[1]+p2[1])/2)
        if n2<n1:
            x1 = int((p1[0]+p3[0])/2)
            y1 = int((p1[1]+p3[1])/2)
        cv2.circle(img,(x1,y1),1,(0,0,255),7)

        if x1 != xb:
            angle=int((math.atan2(yb-y1,xb-x1)*180)/math.pi)
            if angle>=180 :
                angle = angle-180
            if angle<0 :
                angle = -(angle)
        if x1 == xb:
            angle = 90
        perimeter = cv2.arcLength(cntb,True)
        cv2.drawContours(img, contoursb, -1, (255,0,0), 3)
     
        print xb,yb,angle

#cv2.imshow('img',img)
#cv2.waitKey(0)
#cv2.destroyAllWindows()

The above program works fine withe the following images





Cheers!!!!
-> Let Us Embed <-

8051 timers || Tutorial with AT89S52 timer program program

Before going to this tutorial please refer 8051 timers.

Let us see how to configure a timer in 8051 with AT89S52 micro-controller.
After going through the 8051 manual we can implement the same timer logic in this c program to simulate the timer output we can use the LED.
Program:
#include<at89x52.h>
/*
Crystal freq = 11.0592MHz
Fcpu=11.0592MHz
12 Cycles required for one machine cycle
Finstruction=(11.0592/12) MHz => 921.6 KHz
Time period of each machine cycle = 1/921.6 msec.
so... Tmachine cycle = 1.085 uSec
Desired delay = No of counts x 1.085 usec
*/
void configTimer()
{
/*
We need delay for 30mSec Second
So, 30x10^-3 = No of counts x 1.085x10^-6
No of counts = ((30 x 10^-3 x 10^6)/1.085) = 27649 = 0x6C01
Initial timer value = 0xFFFF - 0x6C01 = 0x93FE
THO = 0x93, TL0 = 0xFE
*/
TMOD = 0x1; // Opearating timer 0 in 16bit mode
TH0 = 0x93;
TL0 = 0xFE;
TR0 = 1;//Turn on timer 0
}

void delay()
{
configTimer();
while(TF0 == 0); //wait for timer 0 to overflow
TR0 = 0; //Turn off timer 0
TF0 = 0;//Clear timer 0 overflow flag
}

int main()
{
P1_0 = 0;  //Making 0th pin in port-0 to low i.e LED off
P1_1 = 0;  //Making 1st pin in port-0 to low i.e LED off
while(1)   //Super loop
{
  delay();
  P1_1 = 0; //LED off
  P1_0 = 1; //LED On
  delay();
  P1_0 = 0; //LED off
  P1_1 = 1; //LED on
}
return 0;
}

Connection:


Output Video:



Cheers!!!!
-> Let Us Embed <-

How to install python in windows 10

Let us see how to install python in windows 10 to make the setup for image processing.

Files needed


1)Download all the files above

2)Install python-2.7.5
3)Extract opencv-2.4.11
4)Copy paste cv2.pyd from opencv->build->python->x86 to C:\Python27\Lib\site-packages
3)numpy-1.9.1-win32-superpack-python2.7
4)Site Packages copy paste
5)Set environment - C:\Python27\

Please refer the below video for step by step procedure



Cheers!!!!
-> Let Us Embed <-

PI (π) detector using python | Find the Number of circles in a given image | Image processing

PI (π) detector means detecting circles(rounds). Let us see how we can achieve counting/detecting number of circles/rounds in a given image using python.

Description:

Given an image you have to estimate the number of circularshaped
objects in the image. The
image will have any number of planar circular objects or projections of 3D spheres. The objects
can be of any color. You can assume there will be a contrast between the color of the object
and the background.

Input format:

<program> <input image>
Example :
<program> input.jpg
Output format:
Total number of circular objects

PI (π) Detector code

# import the necessary packages
import numpy as np
import argparse
import sys
import cv2
flag = 0

# load the image, clone it for output, and then convert it to grayscale
#image = cv2.imread('circ2.png')
image = cv2.imread(str(sys.argv[1]))
height,width,channels = image.shape
if width>1000 :
        height = height/2
        width = width/2
        image = cv2.resize(image,(width,height))
output = image.copy()
src = image.copy()
flipped = cv2.flip( src, 1 )
flipped = np.concatenate( (src, flipped), axis = 1 )
src = np.concatenate( (flipped, src), axis = 1 )

flipped = cv2.flip( src, 0 )
flipped = np.concatenate( (src, flipped), axis = 0 )
src = np.concatenate( (flipped, src), axis = 0 )

src = cv2.flip( src, -1 )
output = src.copy()
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray,(9,9),2)
#gray = cv2.bilateralFilter(gray,9,75,75)

# detect circles in the image
circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1,50,param1=40,param2=56,minRadius=0,maxRadius=0)

height = output.shape[0]
width = output.shape[1]
yx = height /3
xx = width / 3
wx = (width / 3)
hx = (height /3)

# ensure at least some circles were found
if circles is not None:
        # convert the (x, y) coordinates and radius of the circles to integers
        circles = np.round(circles[0, :]).astype("int")

        # loop over the (x, y) coordinates and radius of the circles
        for (x, y, r) in circles:
                # draw the circle in the output image, then draw a rectangle
                # corresponding to the center of the circle
                cv2.circle(output, (x, y), r, (0, 255, 0), 4)
                cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
                if ((x > xx) & (x < (wx+xx))) & ((y > yx) & ( y < (hx+yx))):
                        flag = flag + 1

        # show the output image
        #cv2.imshow("input",image)
        #output1 = output[yx: yx + hx, xx: xx + wx]
        #cv2.imshow("output", output1)
        print flag
        #cv2.waitKey(0)
        #cv2.destroyAllWindows()














It works fine with the images above.

Cheers!!!!
-> Let Us Embed <-

CV Scanner using python | Image processing

Let us see the CV Scanner tutorial using python which is used to Scan Papers in a given image.

Description:

You are given a raw image of a sheet of paper ( as shown in the sample ). You are required to
give an output image which correctly segments and orients the sheet.

Input format:

<program> <input image> <output image name>
Example :
<program> input.jpg output.jpg

Output format:

The final image should be written to the filename given in the command line.

import cv2                              
import numpy as np
import math
import argparse
import sys

def order_points(pts):
        # initialzie a list of coordinates that will be ordered
        # such that the first entry in the list is the top-left,
        # the second entry is the top-right, the third is the
        # bottom-right, and the fourth is the bottom-left
        rect = np.zeros((4, 2), dtype = "float32")

        # the top-left point will have the smallest sum, whereas
        # the bottom-right point will have the largest sum
        s = pts.sum(axis = 1)
        rect[0] = pts[np.argmin(s)]
        rect[2] = pts[np.argmax(s)]

        # now, compute the difference between the points, the
        # top-right point will have the smallest difference,
        # whereas the bottom-left will have the largest difference
        diff = np.diff(pts, axis = 1)
        rect[1] = pts[np.argmin(diff)]
        rect[3] = pts[np.argmax(diff)]

        # return the ordered coordinates
        return rect

def four_point_transform(image, pts):
        # obtain a consistent order of the points and unpack them
        # individually
        rect = order_points(pts)
        (tl, tr, br, bl) = rect

        # compute the width of the new image, which will be the
        # maximum distance between bottom-right and bottom-left
        # x-coordiates or the top-right and top-left x-coordinates
        widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
        widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
        maxWidth = max(int(widthA), int(widthB))

        # compute the height of the new image, which will be the
        # maximum distance between the top-right and bottom-right
        # y-coordinates or the top-left and bottom-left y-coordinates
        heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
        heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
        maxHeight = max(int(heightA), int(heightB))

        # now that we have the dimensions of the new image, construct
        # the set of destination points to obtain a "birds eye view",
        # (i.e. top-down view) of the image, again specifying points
        # in the top-left, top-right, bottom-right, and bottom-left
        # order
        dst = np.array([
                [0, 0],
                [maxWidth - 1, 0],
                [maxWidth - 1, maxHeight - 1],
                [0, maxHeight - 1]], dtype = "float32")

        # compute the perspective transform matrix and then apply it
        M = cv2.getPerspectiveTransform(rect, dst)
        warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))

        # return the warped image
        return warped

##ap = argparse.ArgumentParser()
##ap.add_argument("-i", "--image", required = True,
## help = "Path to the image to be scanned")
##args = vars(ap.parse_args())
##
##ap.add_argument("-i", "--oimage", required = True,
## help = "Path to the image to be scanned")
##args1 = vars(ap.parse_args())

image = cv2.imread(str(sys.argv[1]))
ratio = image.shape[0] / 700.0
orig = image.copy()
image = cv2.resize(image, (int(round(image.shape[1]/ratio)),700))

gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray,9,75,75)
ret1,thresh1 = cv2.threshold(gray,175,255,cv2.THRESH_BINARY)

print "STEP 1:  Thresholding"
##cv2.imshow('threshold',thresh1)
##cv2.waitKey(0)
##cv2.destroyAllWindows()

(cnts, _) = cv2.findContours(thresh1.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]

dp = 0.02

length = 0
for c in cnts:
        peri = cv2.arcLength(c, True)
        if peri > length:
                length = peri

# loop over the contours
for c in cnts:
        # approximate the contour
        peri = cv2.arcLength(c, True)
        if peri == length :
                approx = cv2.approxPolyDP(c, dp* peri, True)
                screenCnt = approx

                # if our approximated contour has four points, then we
                # can assume that we have found our screen
                for im in screenCnt:
                        cv2.circle(thresh1,(int(im[0][0]),int(im[0][1])),1,(255,0,0),10)

# show the contour (outline) of the piece of paper
print "STEP 2: Find contours of paper"
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
#cv2.imshow("Outline", image)
#cv2.waitKey(0)
#cv2.destroyAllWindows()

# apply the four point transform to obtain a top-down
# view of the original image
warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)

# convert the warped image to grayscale, then threshold it
# to give it that 'black and white' paper effect
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
#warped1 = cv2.adaptiveThreshold(warped,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
#                               cv2.THRESH_BINARY,11,2)
#warped = warped.astype("uint8") * 255
warped1 = cv2.adaptiveThreshold(warped.astype(np.uint8), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, 3)

# show the original and scanned images
print "STEP 3: Apply perspective transform"
height1,width1,channels1 = orig.shape
height2,width2 = warped.shape
ratio1 = float(height1)/650
ratio2 = float(height2)/650
##cv2.imshow("Original", cv2.resize(orig,(int(round(width1/ratio1)),650)))
##cv2.imshow("Scanned", cv2.resize(warped,(int(round(width2/ratio2)),650)))
##cv2.imshow("Scanned and Thresholded", cv2.resize(warped1,(int(round(width2/ratio2)),650)))
cv2.imwrite(str(sys.argv[2]),warped1)

print "Done"
#cv2.imshow("Scanned", warped)
##cv2.waitKey(0)
##cv2.destroyAllWindows()

This code will detect the paper in a image.
Use this code and check the output with the following images.




It works fine with the images above.

Cheers!!!!
-> Let Us Embed <-