SoFunction
Updated on 2024-11-15

python cv2 intercept irregular region image example

command of knowledge

() function:

Setting a fixed level of threshold applied to a multichannel matrix transforms a grayscale image into a binary image, or removes a specified level of noise, or filters out pixel points that are too small or too large.

Python: (src, thresh, maxval, type[, dst]) → retval, dst

In it:

src: indicates the image source

thresh: indicates the threshold (starting value)

maxval: indicates the maximum value

type: indicates what type of algorithm is used when dividing here, commonly used value is 0 (cv2.THRESH_BINARY)

import cv2 

img = ('')
("src", img)
gray = (img, cv2.COLOR_BGR2GRAY)
ret, dst = (gray, 127, 255, cv2.THRESH_BINARY)
("dst", dst)
(0)

() function:

Find the outline of the detected object

(image, mode, method)

opencv2 returns two values: contours: hierarchy.

Notes.opencv3 will return three values, namely img, countours, hierarchy

In it:

image:represents an image of the search contour;

mode:Indicates the retrieval mode of the profile, of which there are four:

cv2.RETR_EXTERNAL indicates that only the outer contour is detected

cv2.RETR_LIST detected contours do not establish hierarchical relationships

cv2.RETR_CCOMP creates two levels of contours, a top level for the outer boundary and an inner level for the boundary information of the bore. If there is another connected object inside the bore, the boundary of this object is also on the top layer.

cv2.RETR_TREE creates an outline of a hierarchical tree structure.

method:The representation is an approximation of the contours

cv2.CHAIN_APPROX_NONE stores all contour points where the pixel position difference between two neighboring points does not exceed 1, i.e. max(abs(x1-x2), abs(y2-y1)) == 1

cv2.CHAIN_APPROX_SIMPLE compresses elements in the horizontal, vertical, and diagonal directions, retaining only the endpoint coordinates in that direction, e.g., a rectangular outline needs only 4 points to save the outline information

cv2.CHAIN_APPROX_TC89_L1, CV_CHAIN_APPROX_TC89_KCOS using teh-Chinl chain approximation algorithm

import numpy as np 
import cv2

rectangle = ((300,300),dtype="uint8")
(rectangle,(25,25),(275,275),255,-1)
("Rectangle",rectangle)

img, countours, hierarchy = (rectangle, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print(countours)
print(hierarchy)
(0)

[array([[[ 25, 25]],
[[ 25, 275]],
[[275, 275]],
[[275, 25]]], dtype=int32)]

[[[-1 -1 -1 -1]]]

function:

Drawing polygons

(img, pts, isClosed, color[, thickness[, lineType[,shift]]])

First you need the coordinates of the vertices. Convert these points to an array of shape rowsx1x2, where rows is the number of vertices, which should be of type int32.

import numpy as np
import cv2
# Create a black image
img = ((200, 200, 3), np.uint8)

pts = ([[10, 5], [20, 30], [70, 20], [50, 10]], np.int32) # Each point is (x, y) #
pts = ((-1, 1, 2))
(img, [pts], True, (0, 255, 255))

pts = ([[100, 5], [150, 30], [80, 20], [90, 10]], np.int32)
(img, [pts], False, (0, 255, 255))
('img2', img)

()

If the third parameter is False, you will get a polyline connecting all points instead of a closed shape.

() can be used to draw multiple lines. Simply create a list of all the lines to be drawn and pass it to the function, and all lines will be drawn individually. Drawing a group of lines is much better and faster than calling () for each line.

) function

Can be used to fill any shape. It can be used to draw polygons, and is often used to approximate a curve with very many sides. The () function can be used to fill multiple shapes at once.

(image,ppt,Scalar(255,255,255))

image: indicates that the polygon will be drawn on image.

ppt: represents the set of vertices of a polygon as ppt

Scalar: indicates that the polygon's color is defined as Scarlar(255,255,255), i.e. the RGB value is white

img = ((1080, 1920, 3), np.uint8)
area1 = ([[250, 200], [300, 100], [750, 800], [100, 1000]])
area2 = ([[1000, 200], [1500, 200], [1500, 400], [1000, 400]])
 
(img, [area1, area2], (255, 255, 255))
 
(img)
()

Bitwise operations

import numpy as np 
import cv2

rectangle = ((300,300),dtype="uint8")
(rectangle,(25,25),(275,275),255,-1)
("Rectangle",rectangle)

circle = ((300,300),dtype="uint8")
(circle,(150,150),150,255,-1)
("Circle",circle)

bitwiseAnd = cv2.bitwise_and(rectangle,circle)
("And",bitwiseAnd)

bitwiseOr = cv2.bitwise_or(rectangle,circle)
("OR",bitwiseOr)

bitwiseXor = cv2.bitwise_xor(rectangle,circle)
("XOR",bitwiseXor)

bitwiseNot = cv2.bitwise_not(rectangle)
("Not",bitwiseNot)
(0)

If the value of a given pixel is greater than zero, that pixel is turned on, and if it has a value of zero, it is turned off. The per-bit function operates under these binary conditions.

AND:A per-bit AND is true if and only if both pixels are greater than zero.

OR:If either of the two pixels is greater than zero, the bitwise "or" is true.

XOR hetero-or function: per-bit XOR is true if and only if either of the two pixels is greater than zero, but not both. True if and only if one of the two pixels is greater than zero and one is less than zero, but false otherwise

NOT Inverted: Inverts the "on" and "off" pixels in the image.

# -*- coding: utf-8 -*-
 
import cv2
import numpy as np
global img
global point1, point2
 
lsPointsChoose = []
tpPointsChoose = []
 
pointsCount = 0
count = 0 
pointsMax = 5
 
lsPointsChoose = []
tpPointsChoose = []
 
pointsCount = 0
count = 0
pointsMax = 5

 
def on_mouse(event, x, y, flags, param):
  global img, point1, point2, count, pointsMax
  global lsPointsChoose, tpPointsChoose # Access to selected points
  global pointsCount # Counts the points of mouse presses
  global init_img, ROI_bymouse_flag
  init_img = () # This line of code ensures that the original drawing is redrawn each time to avoid overdrawing #

  if event == cv2.EVENT_LBUTTONDOWN: # Left click
 
    pointsCount = pointsCount + 1
    # Points drawn are zeroed out a little later in order to preserve the drawn area
    if(pointsCount == pointsMax + 1):
      pointsCount = 0
      tpPointsChoose = []
    print('pointsCount:', pointsCount)
    point1 = (x, y)
    print (x, y)
    # Draw the point of the click
    (init_img, point1, 10, (0, 255, 0), 5)
 
    # Save the selected points to the list list
    ([x, y]) # Used to convert to darry Extract polygon ROIs
    ((x, y)) # For drawing points

    # Link mouse-selected points with a straight line
    print(len(tpPointsChoose))
    for i in range(len(tpPointsChoose) - 1):
      (init_img, tpPointsChoose[i], tpPointsChoose[i + 1], (0, 0, 255), 5)
    # Extract the drawing when clicking on pointMax
    if(pointsCount == pointsMax):
      # Mapping areas of interest
      ROI_byMouse()
      ROI_bymouse_flag = 1
      lsPointsChoose = []
 
    ('src', init_img)
    
  # Right-click to clear the track
  if event == cv2.EVENT_RBUTTONDOWN: # Right-click
    print("right-mouse")
    pointsCount = 0
    tpPointsChoose = []
    lsPointsChoose = []
    print(len(tpPointsChoose))
    for i in range(len(tpPointsChoose) - 1):
      print('i', i)
      (init_img, tpPointsChoose[i], tpPointsChoose[i + 1], (0, 0, 255), 5)
    ('src', init_img)


def ROI_byMouse():
  global src, ROI, ROI_flag, mask2
  mask = (, np.uint8)
  pts = ([lsPointsChoose], np.int32)

  pts = ((-1, 1, 2)) # -1 means that the remaining dimensions are automatically calculated

  # Draw polygons
  mask = (mask, [pts], True, (0, 255, 255))
  # Filled polygons
  mask2 = (mask, [pts], (255, 255, 255))
  ('mask', mask2)
  ROI = cv2.bitwise_and(mask2, img)
  ('ROI', ROI)

  
def main():
  global img, init_img, ROI
  img = ('')  
 
  # image preprocessing, set its size
  height, width = [:2]  
  size = (int(width * 0.3), int(height * 0.3)) 
  img = (img, size, interpolation=cv2.INTER_AREA)  
  ROI = ()
  ('src')
  ('src', on_mouse)  
  ('src', img)
  (0)
  ()


if __name__ == '__main__':
  main()

Above this python cv2 intercept irregular area picture example is all I have shared with you, I hope it can give you a reference, and I hope you can support me more.