Tag Archives: opencv

Direct Drawing a rectangle on Images with a mouse with OpenCV Python

import cv2
import numpy as np

is_drawing = False
ix = -1
iy = -1

blank_image = np.zeros([512, 512, 3], dtype=np.uint8)


def draw_rectangle(event, x, y, flags, param):
    global is_drawing, ix, iy

    if event == cv2.EVENT_LBUTTONDOWN:
        is_drawing = True
        ix = x
        iy = y
    elif event == cv2.EVENT_LBUTTONUP:
        is_drawing = False
        cv2.rectangle(img=blank_image, pt1=(ix, iy), pt2=(x, y), color=(255, 0, 0), thickness=-1)
        ix = -1
        iy = -1
    elif event == cv2.EVENT_MOUSEMOVE:
        if is_drawing:
            cv2.rectangle(img=blank_image, pt1=(ix, iy), pt2=(x, y), color=(255, 0, 0), thickness=-1)


cv2.namedWindow("image")
cv2.setMouseCallback("image", draw_rectangle)

while True:
    cv2.imshow("image", blank_image)

    # wait 5 seconds then wait for ESC key
    if cv2.waitKey(5) & 0xFF == 27:
        break

cv2.destroyAllWindows()

References
https://github.com/mhdr/OpenCVSamples/tree/master/011

Direct Drawing on Images with a mouse with OpenCV Python

import cv2
import numpy as np

blank_image = np.zeros([512, 512, 3], dtype=np.uint8)


def draw_circle(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        cv2.circle(blank_image, center=(x, y), radius=20, color=(0, 0, 255), thickness=-1)
    elif event == cv2.EVENT_RBUTTONDOWN:
        cv2.circle(blank_image, center=(x, y), radius=20, color=(0, 255, 0), thickness=-1)


cv2.namedWindow("image")
cv2.setMouseCallback("image", draw_circle)

while True:
    cv2.imshow("image", blank_image)

    # wait 5 seconds then wait for ESC key
    if cv2.waitKey(5) & 0xFF == 27:
        break

cv2.destroyAllWindows()

References
https://github.com/mhdr/OpenCVSamples/tree/master/011

Create blank image using OpenCV Python

import cv2
import numpy as np

# black blank image
blank_image = np.zeros(shape=[512, 512, 3], dtype=np.uint8)
# print(blank_image.shape)
cv2.imshow("Black Blank", blank_image)

# white blank image
blank_image2 = 255 * np.ones(shape=[512, 512, 3], dtype=np.uint8)
cv2.imshow("White Blank", blank_image2)

cv2.waitKey(0)
cv2.destroyAllWindows()

References
https://stackoverflow.com/questions/10465747/how-to-create-a-white-image-in-python
https://github.com/mhdr/OpenCVSamples/tree/master/010

Flip image in OpenCV Python

import cv2
import numpy as np

image = cv2.imread("cow.jpg")
cv2.imshow("image", image)

# flip horizontally
flipped1 = cv2.flip(image, 0)
cv2.imshow("image1", flipped1)

# flip vertically
flipped2 = cv2.flip(image, 1)
cv2.imshow("image2", flipped2)

# flip both horizontally and vertically
flipped3 = cv2.flip(image, -1)
cv2.imshow("image3", flipped3)

cv2.waitKey(0)
cv2.destroyAllWindows()

References
https://github.com/mhdr/OpenCVSamples/tree/master/009

Resize image in OpenCV Python

import cv2
import numpy as np

image = cv2.imread("cow.jpg")
print(image.shape)  # (559, 838, 3)

old_width = image.shape[1]  # 838
old_height = image.shape[0]  # 559

# resize by custom size
new_width = 600
new_height = 400
resized = cv2.resize(image, (new_width, new_height))
cv2.imshow("image", resized)

# resize by ratio
width_ratio = 0.5
height_ration = 0.5
resized2 = cv2.resize(image, (0, 0), image, width_ratio, height_ration)
cv2.imshow("image2", resized2)

cv2.waitKey(0)
cv2.destroyAllWindows()

References
https://github.com/mhdr/OpenCVSamples/tree/master/008

Image Operations with OpenCV Python

Read Pixel

import cv2
import numpy as np
import pprint

image = cv2.imread('cow.jpg',cv2.IMREAD_COLOR)
pixel= image[55,55]
pprint.pprint(pixel)

Change Pixel

import cv2
import numpy as np
import pprint

image = cv2.imread('cow.jpg', cv2.IMREAD_COLOR)
image[55, 55] = [255, 255, 255]
pixel = image[55, 55]
pprint.pprint(pixel)

Change the color of Region of Image

import cv2
import numpy as np
import pprint

image = cv2.imread('cow.jpg', cv2.IMREAD_COLOR)
image[150:200, 100:150] = [255, 255, 255]
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Image Characteristics 

import cv2
import numpy as np
import pprint

image = cv2.imread('cow.jpg', cv2.IMREAD_COLOR)
print(image.shape)
print(image.size)
print(image.dtype)

Copy Paste Region

import cv2
import numpy as np
import pprint

image = cv2.imread('cow.jpg', cv2.IMREAD_COLOR)

watch_face = image[200:250,107:194]
image[0:50,0:87] = watch_face

cv2.imshow('image',image)
cv2.waitKey(0)
cv2.destroyAllWindows()

References
https://pythonprogramming.net/image-operations-python-opencv-tutorial/
https://www.youtube.com/watch?v=1pzk_DIL_wo&list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq&index=4
https://github.com/mhdr/OpenCV/tree/master/004

Drawing and Writing on Image with OpenCV Python

Drawing Line

# Draw a diagonal blue line with thickness of 5 px
cv.line(img,(0,0),(511,511),(255,0,0),5)

Drawing Rectangle

cv.rectangle(img,(384,0),(510,128),(0,255,0),3)

Drawing Circle

cv.circle(img,(447,63), 63, (0,0,255), -1)

Drawing Ellipse

cv.ellipse(img,(256,256),(100,50),0,0,180,255,-1)

Drawing Polygon

pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
pts = pts.reshape((-1,1,2))
cv.polylines(img,[pts],True,(0,255,255))

Adding Text to Images

font = cv.FONT_HERSHEY_SIMPLEX
cv.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv.LINE_AA)

References
https://docs.opencv.org/4.0.1/dc/da5/tutorial_py_drawing_functions.html
https://www.youtube.com/watch?v=U6uIrq2eh_o&list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq&index=3
https://pythonprogramming.net/drawing-writing-python-opencv-tutorial/
https://github.com/mhdr/OpenCV/tree/master/003

Capture Video and Save it using OpenCV Python

cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID') # specify the codec
out=cv2.VideoWriter('output.avi',fourcc,20.0,(640,480))

while True:
    ret, frame = cap.read()
    cv2.imshow("frame", frame)
    out.write(frame)

    # exit video capture
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

References
https://www.youtube.com/watch?v=Jvf5y21ZqtQ
https://github.com/mhdr/OpenCV/tree/master/002

Capture Video and make Grayscale using OpenCV Python

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow("gray", gray)

    # exit video capture
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()

References
https://www.youtube.com/watch?v=Jvf5y21ZqtQ
https://github.com/mhdr/OpenCV/tree/master/002