This blog will show you how to create blank canvas, white canvas and color canvas using NUMpy and CV2. Creating canvas is the premise of making drawing tools. With canvas, we can paint our own artistic cells on the canvas.

Still for how to go to drawing trouble small partners quickly look over, here hand in hand teach you to solve the problem ~~~~

Of course, there are rules: like it first, respect the author. Young people still need to talk about martial arts…

Without further ado, let’s get to the point

1. Create a blank canvas

Define a function to pass the width and height of the image and the color of the canvas. The RGB value of the blank canvas color is (255,255,255).

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

For example, create a 500*500 canvas with a solid black color on this blank canvas, which can be expressed as:

canvas = InitCanvas(500.500, color=(0.0.0))
Copy the code

The complete code is as follows:

Initialize the canvas.
import cv2
import numpy as np

def InitCanvas(width, height, color=(255.255.255)) :
    canvas = np.ones((height, width, 3), dtype="uint8")
    canvas[:] = color
    return canvas

canvas = InitCanvas(500.500, color=(0.0.0))
cv2.imshow('canvas', canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()
Copy the code

Creating a canvas is essentially creating a Numpy nDARray object of the same size. 2. 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. Uint8 Unsigned INTEGER 8-bit (uint8) np.zeros((height, width, channels), dtype=”uint8″)

2. Initialize the white canvas

Methods a

Create a blank canvas and change the color to (255,255,255), you can get a white canvas, the code is as follows:

import cv2
import numpy as np

def InitCanvas(width, height, color=(255.255.255)) :
    canvas = np.ones((height, width, 3), dtype="uint8")
    canvas[:] = color
    return canvas

canvas = InitCanvas(500.500, color=(255.255.255))
cv2.imshow('canvas', canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()
Copy the code

Method 2

The first thing that comes to mind is white, and because it’s relatively simple, 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, and then multiply it by some number, and we’re done.

We need to use the Np. ones function

Initialize an empty canvas with a 500×500 three-channel background color of white
canvas = np.ones((500.500.3), dtype="uint8")
Copy the code

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

canvas_white *= 255
Copy the code

The complete implementation code is as follows, and the result is the same as method one:

import cv2
import numpy as np

canvas = np.ones((500.500.3), dtype="uint8")
canvas *= 255

cv2.imshow('canvas', canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()
Copy the code

3. Initialize the colored canvas

3.1 Use cV2’s built-in methods merge and split

After initializing the picture canvas of BGR, we separated the original picture by the 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 picture we wanted.

Split (img) cv2.split(img)

# Separate the original three channels and multiply them by the values of each channel
(channel_b, channel_g, channel_r) = cv2.split(canvas)
Copy the code
  • channel_bThe blue channel
  • channel_ggreen channel
  • channel_rThe red channel
  • It’s all two-dimensionalndarrayobject

We specify a color, for example color = (140, 30, 60)

Note that our color here refers to the BGR format

That is

B -> 140
G -> 30
R -> 60
Copy the code

And then I’m going to multiply each of these times the corresponding value

The value of the color is multiplied by the full 1 matrix of each channel
channel_b *= color[0]
channel_g *= color[1]
channel_r *= color[2]
Copy the code

Merge the three channels again using cv2.merge as follows:

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

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

Based on the above function to initialize the color background, it can be expressed as:

Initialize the canvas.
import cv2
import numpy as np

# Initialize a colorful canvas - cV2 version
def InitCanvas(width, height, color=(255.255.255)) :
    canvas = np.ones((height, width, 3), dtype="uint8")

    # Separate the original three channels and multiply them by the values of each channel
    (channel_b, channel_g, channel_r) = cv2.split(canvas)
    The value of the color is multiplied by the full 1 matrix of each channel
    channel_b *= color[0]
    channel_g *= color[1]
    channel_r *= color[2]

    CV. Merge Merges the values of the three channels
    return cv2.merge([channel_b, channel_g, channel_r])

canvas = InitCanvas(500.500, color=(140.30.60))
cv2.imshow('canvas', canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()
Copy the code

Canvas = InitCanvas(500, 500, color=(140, 30,60))Inside the color can be customized between 0 and 255 values.

3.2 Utilize numpy’s built-in indexes

The above method is time-consuming to create and may not be used by perfectionists. So here’s another way:

Methods native to Numpy perform better than those in OpencV.

You can use numpy’s darray index method directly.

For example: Canvas [:,:,0] selects the first value of all row and column pixel elements, i.e., values of all B channels. It is then assigned:

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

Specific use is shown as follows:

The complete code used is as follows:

Initialize the canvas.
import cv2
import numpy as np

def InitCanvas(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 = InitCanvas(500.500, color=(125.50.255))

cv2.imshow('canvas', canvas)
cv2.waitKey(0)

cv2.destroyAllWindows()
Copy the code

4. Comprehensive experiment – initialization background

Black background, white background and color background will be created in this comprehensive experiment.

Initializes a blank canvas and specifies the color of the canvas.
import cv2
import numpy as np

Initialize an empty canvas with a 500×500 three-channel background color to black
canvas_black = np.zeros((500.500.3), dtype="uint8")
cv2.imshow("canvas_black", canvas_black)

Initialize an empty canvas with a 500×500 three-channel background color of white
canvas_white = np.ones((500.500.3), dtype="uint8")
canvas_white *= 255

cv2.imshow("canvas_white", canvas_white)

Initialize a colored canvas - CV2 version"
def InitCanvasV1(width, height, color=(255.255.255)) :
    canvas = np.ones((height, width, 3), dtype="uint8")

    # Separate the original three channels and multiply them by the values of each channel
    (channel_b, channel_g, channel_r) = cv2.split(canvas)
    The value of the color is multiplied by the full 1 matrix of each channel
    channel_b *= color[0]
    channel_g *= color[1]
    channel_r *= color[2]

    CV. Merge Merges the values of the three channels
    return cv2.merge([channel_b, channel_g, channel_r])

Initialize a colored canvas - numpy version using numpy's index assignment.
def InitCanvasV2(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

Initialize the final version.
def InitCanvasV3(width, height, color=(255.255.255)) :
    canvas = np.ones((height, width, 3), dtype="uint8")
    canvas[:] = color
    return canvas

Initialize a colorful canvas
canvas_color = InitCanvasV2(500.500, color=(100.20.50))
cv2.imshow("canvas_color", canvas_color)

# Wait for the E key to close all Windows
while cv2.waitKey(0) != ord('e') :continue
cv2.destroyAllWindows()
Copy the code

Resource portal

  • Pay attention to [be a gentle program ape] public account
  • In [do a tender program ape] public account background reply [Python information] [2020 autumn recruit] can get the corresponding surprise oh!
  • Build their own blog address: nightmare back to life blog

“❤️ thank you.”

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