Author: YWSYdWSBN blog home page: blog.csdn.net/ywsydwsbn public number: “do a tender feeling of the program ape” time: 2020-10-06 20:57 words: 7889 introduction: the first praise in see, form a habit!!

The article directories

  • Abstract
  • Numpy’s NDARray data structure index and assignment
  • Create a blank canvas
  • Initialize the white canvas
  • Initialize the colored canvas
    • Use cV2’s built-in methods merge and split
    • Take advantage of numpy’s built-in indexes
  • Comprehensive experiment – initialization background
  • Resource portal
  • “❤️ thank you.”

Abstract

In this article we will show you how to create a blank canvas using NUMpy, a white canvas using NUMpy and Cv2, and a color canvas using numpy. In the course of explanation, we will also introduce the specific use of cv2 channel splitting cv2.split and channel merging cv2.merge as well as the index and assignment of NUMpy’s NDARray data structure.

Numpy’s NDARray data structure index and assignment

When using the drawing tool, the first thing we do is create a new blank canvas. We can specify the size and color of the canvas.

So how do we use OpencV to create a blank canvas (with the same value of the image)?

So the image on the data structure of image is essentiallynumpyThe inside of theThe object of ndarrayCreating a canvas is essentially creating a canvas of the same sizendarray.

To create a new nDARray of a specific size we can use the np.zeors function. We pass the height of the image, the width of the image, and the number of channels of the image into NP. Zeros as a tuple. Again, tuple.

In addition, not all numpy values can be put into OpencV for image processing.

Values range from 0 to 255, we need to specify the data type as uint8 unsigned INTEGER 8-bit

np.zeros((height, width, channels), dtype="uint8")
1
Copy the code

For example: to create an 800 x 600 x 3 image, a BGR image, we would write:

Canvas_black = Np.zeros ((600, 800, 3), dtype="uint8") 12Copy the code

The results are as follows:

Notice: height in front why height in front? You have to know that the data structure of the OpencV Image is numpy, and the property of the Image is actually the property of numpy’s NDARray data format.

We can directly obtain many attributes of the IMG object. For example, we print the attributes of the Lena graph, as follows:

# -*- coding: Utf-8 -* -import numpy as np import cv2 # img = cv2.imread('lena.jpg', Cv2. IMREAD_COLOR) print (" = = = = = = = = = = = = = = = = to print the image attributes of = = = = = = = = = = = = = = = = ") print (" the type of image object {} ". The format (type (img))) Format (img.shape[1]) print(" image height: {} pixels". Format (img.shape[0])) print(" image height: {} pixels". {}".format(img.shape[2]) print(" image resolution: {}".format(img.size)) print(" Datatype: {}".format(img.dtype)) 123456789101112131415Copy the code

Output result:

= = = = = = = = = = = = = = = = to print the image attributes of = = = = = = = = = = = = = = = = image object of type < class 'numpy. Ndarray' > (256, 256, 3) image width: 256 pixels image height: Image resolution: 196608 Data type: Uint8 12345678Copy the code

Sometimes we can be lazy and use Np.zerOS_like if we want to create a canvas of the same size as another image

canvas_black = np.zeros_like(img)
1
Copy the code

Create a blank canvas

The function to create a blank canvas looks like this:

def InitCanvas(width, height, color=(255, 255, 255)):
    canvas = np.ones((height, width, 3), dtype="uint8")
    canvas[:] = color
    return canvas
1234
Copy the code

Call to pass in the width, height, and canvas color of the image. For example, create an 800*600 canvas with a solid black color:

Canvas = InitCanvas(800, 600, color=(255,255,255)) 1Copy the code

The complete code to create a blank canvas is as follows:

Import cv2 import numpy as np def init_canvas(width, height, color=(255, 255, 255)): canvas = np.ones((height, width, 3), dtype="uint8") canvas[:] = color return canvas canvas = init_canvas(200, 200, color=(125, 40, 255)) cv2.imshow('canvas', canvas) cv2.waitKey(0) cv2.destroyAllWindows() 1234567891011121314151617Copy the code

Effect display:

Initialize the white canvas

White canvas, because it’s simpler, and all three channels have the same value.

Ps: In fact, the gray picture (GRAY2BGR) has the same values for all three channels.

So let’s create a matrix of all ones, multiply it by some number, and we’re done.

We need to use the Np. ones function

Canvas_white = Np.ones ((300, 300, 3), dtype="uint8") 12Copy the code

Next, you need to multiply by an integer, 255 (you can fill in any value from 0 to 255).

canvas_white *= 255
1
Copy the code

This operation is called global multiplication.

The specific code is as follows:

import cv2
import numpy as np
canvas_white = np.ones((300, 300, 3), dtype="uint8")
canvas_white *= 255
cv2.imshow('canvas', canvas_white)
cv2.waitKey(0)
cv2.destroyAllWindows()
1234567
Copy the code

Create the white canvas as follows:

Initialize the colored canvas

Use cV2’s built-in methods merge and split

After initializing the picture canvas_white of BGR, we separated the original picture by channels, multiplied the integral values of the three channels of BGR respectively, and then merged the three channels together to obtain the solid color background of the color image we want.

The function we need to split the channel is cv2.split(img).

Split (canvas) 12 (channel_b, channel_g, channel_r) = cv2.split(canvas) 12Copy the code

Channel_b blue channel, channel_g green channel, and channel_r red channel are all two-dimensional NDARray objects.

We specify a color, for example color = (100, 20, 50).

Note: Our color here refers to the BGR format

That is

B -> 100

G -> 20

R -> 50

And then we’re going to multiply them by their respective values.

Channel_b *= color[0] channel_g *= color[1] channel_r *= color[2] 1234Copy the code

Next we remerge the three channels using a function called cv2.merge

cv2.merge([channel_b, channel_g, channel_r])
1
Copy the code

Note: The three-channel matrix is passed into the merge function as list [].

Together, this is our first function that initializes the color background:

Def init_canvas(width, height, color=(255, 255, 255)): Canvas = np.ones((height, width, 3), dtype="uint8") Multiply the values of each channel (channel_B, channel_g, Channel_b *= color[0] channel_g *= color[1] channel_r *= color[2] # CV. Merge Merge values of three channels return cv2.merge([channel_B, channel_g, channel_r]) 12345678910111213Copy the code

The specific implementation code is as follows:

Def init_canvas(width, height, color=(255, 255)) def init_canvas(width, height, color=(255, 255)): Canvas = np.ones((height, width, 3), dtype="uint8") Multiply the values of each channel (channel_B, channel_g, Channel_b *= color[0] channel_g *= color[1] channel_r *= color[2] # Cv2. merge([channel_b, channel_g, channel_r]) canvas = init_canvas(200, 200, color=(125, 100, 255)) cv2.imshow('canvas', canvas) cv2.waitKey(0) cv2.destroyAllWindows() 1234567891011121314151617181920212223242526Copy the code

Operation effect:

Note: This function is time-consuming using cv2.split so it can only be done if needed. Otherwise use Numpy index.

Take advantage of numpy’s built-in indexes

Using numpy native methods, performance is better than in OpencV. We use numpy’s darray index method directly.

For example, canvas[:,:,0] selects the first value of all rows, all columns, pixel elements, i.e., all B channels.

It is then assigned:

canvas[:,:,0] = color[0]
1
Copy the code

The full version of the function looks like this, with B/G/R channels assigned separately:

def init_canvas(width, height, color=(255, 255, 255)):
    canvas = np.ones((height, width, 3), dtype="uint8")
    # Blue 
    canvas[:,:,0] = color[0]
    # Green
    canvas[:,:,1] = color[1]
    # Red
    canvas[:,:,2] = color[2]

    return canvas
12345678910
Copy the code

The specific implementation code is as follows:

Import cv2 import numpy as np def init_canvas(width, height, color=(255, 255, 255)): canvas = np.ones((height, width, 3), dtype="uint8") # Blue canvas[:,:,0] = color[0] # Green canvas[:,:,1] = color[1] # Red canvas[:,:,2] = color[2] return canvas canvas = init_canvas(200, 200, color=(125, 100, 255)) cv2.imshow('canvas', canvas) cv2.waitKey(0) cv2.destroyAllWindows() 1234567891011121314151617181920212223Copy the code

Running the implementation has the same effect as the first method:



There are actually faster ways to do this, which require you to master Numpy.

We can assign color directly

canvas[:] = color
1
Copy the code

The complete implementation process is as follows:

Import cv2 import numpy as np def init_canvas(width, height, color=(255, 255, 255)): canvas = np.ones((height, width, 3), dtype="uint8") canvas[:] = color return canvas canvas = init_canvas(200, 200, color=(125, 40, 255)) cv2.imshow('canvas', canvas) cv2.waitKey(0) cv2.destroyAllWindows() 1234567891011121314151617Copy the code

Effect of operation:

Comprehensive experiment – initialization background

In this comprehensive experiment, the above methods will be used to create black background, white background and color background respectively.

The specific code is as follows:

Import cv2 import numpy as NP # Initialize an empty canvas 300×300 three-channel background color is black canvas_black = Np.zeros ((300, 300, 3), dtype="uint8") cv2.imshow("canvas_black", Canvas_white = Np.ones ((300, 300, 3)) # initialize an empty canvas 300×300 three channel background color to white dtype="uint8") canvas_white *= 255 cv2.imshow("canvas_white", Canvas_white) "" initializes a colored canvas - cv2 version This function uses cv2.split is time-consuming so it can only be done when needed. Otherwise use Numpy index. ''' def InitCanvasV1(width, height, color=(255, 255, 255)): Canvas = np.ones((height, width, 3), dtype="uint8") Multiply the values of each channel (channel_B, channel_g, Channel_b *= color[0] channel_g *= color[1] channel_r *= color[2] # CV. Merge Merge values of three channels return cv2.merge([channel_b, channel_g, Def InitCanvasV2(width, height, color=(255, 255, 255)) def InitCanvasV2(width, height, color=(255, 255)) canvas = np.ones((height, width, 3), dtype="uint8") # Blue canvas[:,:,0] = color[0] # Green canvas[:,:,1] = color[1] # Red canvas[:,:,2] = color[2] return Def InitCanvasV3(width, height, color=(255, 255)) def InitCanvasV3(width, height, color=(255, 255)): canvas = np.ones((height, width, 3), Canvas_color = InitCanvasV2(300, 300, color=(100, 20, 50)) cv2.imshow("canvas_color", canvas_color) # wait while cv2.waitKey(0)! = ord('e'): continue cv2.destroyAllWindows() 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646 56667686970Copy the code

Running results:

Resource portal

  • Pay attention to the

    Be a soft programmer

    】 the public no.

  • In the 【

    Be a soft programmer

    【python information 】【2020 autumn recruitment 】 you can get the corresponding surprise oh!

“❤️ thank you.”

  1. Click “like” to support it, so that more people can see this content.
  2. Share your thoughts with me in the comments section, and record your thought process in the comments section.