Draw a rectangle around a region of interest in OpenCV Python

# Python program to explain cv2.rectangle() method 

# importing cv2 
import cv2 

# path 
path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'

# Reading an image in default mode 
image = cv2.imread(path) 

# Window name in which image is displayed 
window_name = 'Image'

# Start coordinate, here (5, 5) 
# represents the top left corner of rectangle 
start_point = (5, 5) 

# Ending coordinate, here (220, 220) 
# represents the bottom right corner of rectangle 
end_point = (220, 220) 

# Blue color in BGR 
color = (255, 0, 0) 

# Line thickness of 2 px 
thickness = 2

# Using cv2.rectangle() method 
# Draw a rectangle with blue line borders of thickness of 2 px 
image = cv2.rectangle(image, start_point, end_point, color, thickness) 

# Displaying the image 
cv2.imshow(window_name, image) 
k = cv2.waitKey(0) # 0==wait forever

References
https://www.geeksforgeeks.org/python-opencv-cv2-rectangle-method/
https://stackoverflow.com/questions/23720875/how-to-draw-a-rectangle-around-a-region-of-interest-in-python

Template Matching using OpenCV Python

image_gray: np.ndarray
TM_METHOD=cv2.TM_CCOEFF_NORMED

def __init__(self):
    self.take_screenshot()

def take_screenshot(self):
    user32 = ctypes.windll.user32
    user32.SetProcessDPIAware()
    image = ImageGrab.grab()
    # save on file
    # image.save('screenshot.jpg', format='JPEG', quality=20)

    # load image from memory
    image_rgb = np.array(image)

    # load from file
    # image_rgb=cv2.imread('screenshot.jpg')
    self.image_gray = cv2.cvtColor(image_rgb, cv2.COLOR_BGR2GRAY)

@staticmethod
def save_screenshot():
    user32 = ctypes.windll.user32
    user32.SetProcessDPIAware()
    image = ImageGrab.grab()
    image.save("screenshot.jpg")

def template_available(self, template_path: str, threshold=0.9):

    # self.take_screenshot()

    template = cv2.imread(template_path, 0)
    # w, h = template.shape[::-1]

    res = cv2.matchTemplate(self.image_gray, template, self.TM_METHOD)
    loc = np.where(res >= threshold)

    if len(loc[0]) == 0 & len(loc[1]) == 0:
        return False
    else:
        print("template_available : " + template_path)
        return True

def template_count(self, template_path: str, threshold=0.9):

    # self.take_screenshot()

    template = cv2.imread(template_path, 0)
    # w, h = template.shape[::-1]

    res = cv2.matchTemplate(self.image_gray, template, self.TM_METHOD)
    loc = np.where(res >= threshold)

    return len(loc[0])

def template_location(self, template_path: str, threshold=0.9):

    self.take_screenshot()

    template = cv2.imread(template_path, 0)
    w, h = template.shape[::-1]

    res = cv2.matchTemplate(self.image_gray, template, self.TM_METHOD)
    loc = np.where(res >= threshold)

    if len(loc[0]) == 0 & len(loc[1]) == 0:
        return None
    else:
        click_y = loc[0][0] + h / 2
        click_x = loc[1][0] + w / 2

        return click_x, click_y

def move_mouse_to_template(self, template_path: str):
    loc = self.template_location(template_path)

    if loc is not None:
        click_x = loc[0]
        click_y = loc[1]
        pyautogui.moveTo(click_x, click_y)

def click_template(self, template_path: str, threshold=0.9):
    loc = self.template_location(template_path, threshold)

    if loc is not None:
        click_x = loc[0]
        click_y = loc[1]
        pyautogui.click(click_x, click_y)
        pyautogui.FAILSAFE = False
        pyautogui.moveTo(0, 0)
        print("click_template : " + template_path)
        return True

    return False

@staticmethod
def scroll_mouse(value=10):
    pyautogui.scroll(value)
    pyautogui.FAILSAFE = False
    pyautogui.moveTo(0, 0)

@staticmethod
def get_template_path(template: str):
    template_name = f"template{template}.jpg"
    template_path = os.path.join(os.getcwd(), 'templates', template_name)
    return template_path

 

Template Matching On Images C# using OpenCV

Image<Bgr, byte> Image1 = new Image<Bgr, byte>(Properties.Resources.Image1); //Your first image
        Image<Bgr, byte> Image2 = new Image<Bgr, byte>(Properties.Resources.Image2); //Your second image

        double Threshold = 0.8; //set it to a decimal value between 0 and 1.00, 1.00 meaning that the images must be identical

        Image<Gray, float> Matches = Image1.MatchTemplate(Image2, TemplateMatchingType.CcoeffNormed);

        for (int y = 0; y < Matches.Data.GetLength(0); y++)
        {
            for (int x = 0; x < Matches.Data.GetLength(1); x++)
            {
                 if (Matches.Data[y, x, 0] >= Threshold) //Check if its a valid match
                 {
                     //Image2 found within Image1
                 }
            }
        }

References
https://stackoverflow.com/questions/39570033/template-matching-on-images-c-sharp

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