OpenCV learning lesson from scratch - 4. Addition and superposition of images
This series is for Python Xiaobai and explains the actual combat of OpenCV project from scratch.
This section introduces image addition, superposition and mixing, and provides complete routines and running results: addition operation, weighted addition, image mixing, switching, masking and superposition, and adding text. This paper introduces in detail the comprehensive use of image threshold processing, image mask, bit operation and image addition. It is a method to realize image superposition based on mask and bit operation.
1. Image addition
The function cv2.add() is used for image addition.
Function Description:
cv2.add(src1, src2 [, dst[, mask[, dtype]]) → dst
The function cv2.add() adds two images of the same size and type, or adds an image to a scalar.
When two images are added, the channel values or gray values of pixels at the same position of the two images are added respectively, which can be understood as an image superposition method; When an image is added to a scalar, the channel values of all pixels of the image are added to the channel values of the scalar respectively.
Parameter Description:
- scr1, scr2: an image for addition, or an image and a numpy array scalar
- dst: output image; optional; the default value is None
- Mask: mask image, 8-bit grayscale format; For a pixel with a mask image value of 0, each channel value of the pixel corresponding to the output image is also 0. Optional. The default value is None
- dtype: the depth of the image array, that is, the number of bits of each pixel value. Optional
- Return value: dst, operation result image, ndarray multidimensional array
matters needing attention:
- There is a difference between OpenCV addition and numpy addition: cv2.add() is a saturation operation (if it is greater than 255 after addition, the result is 255), while numpy addition is a modular operation.
- When adding two pictures using the cv2.add() function, the size and type (number of channels) of the pictures must be the same.
- Use the cv2.add() function to add an image to a scalar, which refers to a 1x3 numpy array. After adding, the image turns white as a whole.
Basic routine: 1.22 image addition
# 1.22 image addition (cv2.add) img1 = cv2.imread("../images/imgB1.jpg") # Read color image (BGR) img2 = cv2.imread("../images/imgB3.jpg") # Read color image (BGR) imgAddCV = cv2.add(img1, img2) # OpenCV addition: saturation operation imgAddNP = img1 + img2 # # Numpy addition: modular operation plt.subplot(221), plt.title("1. img1"), plt.axis('off') plt.imshow(cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)) # Display img1(RGB) plt.subplot(222), plt.title("2. img2"), plt.axis('off') plt.imshow(cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)) # Display img2(RGB) plt.subplot(223), plt.title("3. cv2.add(img1, img2)"), plt.axis('off') plt.imshow(cv2.cvtColor(imgAddCV, cv2.COLOR_BGR2RGB)) # Show imgAddCV(RGB) plt.subplot(224), plt.title("4. img1 + img2"), plt.axis('off') plt.imshow(cv2.cvtColor(imgAddNP, cv2.COLOR_BGR2RGB)) # Show imgAddNP(RGB) plt.show()
Routine description 1.22:
The running result of this routine is shown in the figure below. Fig. 3 is the result of cv2.add() saturation addition, and Fig. 4 is the result of numpy modular addition.
- Saturation addition takes 255 as the upper limit, and all pixels will only become whiter (greater than the original value); If the modulo addition takes 255 as the modulus, some pixels will become black (less than the original value).
- Therefore, in general, cv2.add should be used for saturation addition, and numpy modular addition should not be used.
Basic routine: 1.23 image and scalar addition
# 1.23 image addition (adding with scalar) img1 = cv2.imread("../images/imgB1.jpg") # Read color image (BGR) img2 = cv2.imread("../images/imgB3.jpg") # Read color image (BGR) Value = 100 # constant # Scalar = np.array([[50., 100., 150.]]) # scalar Scalar = np.ones((1, 3), dtype="float") * Value # scalar imgAddV = cv2.add(img1, Value) # OpenCV addition: image + constant imgAddS = cv2.add(img1, Scalar) # OpenCV addition: image + scalar print("Shape of scalar", Scalar) for i in range(1, 6): x, y = i*10, i*10 print("(x,y)={},{}, img1:{}, imgAddV:{}, imgAddS:{}" .format(x,y,img1[x,y],imgAddV[x,y],imgAddS[x,y])) plt.subplot(131), plt.title("1. img1"), plt.axis('off') plt.imshow(cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)) # Display img1(RGB) plt.subplot(132), plt.title("2. img + constant"), plt.axis('off') plt.imshow(cv2.cvtColor(imgAddV, cv2.COLOR_BGR2RGB)) # Show imgAddV(RGB) plt.subplot(133), plt.title("3. img + scalar"), plt.axis('off') plt.imshow(cv2.cvtColor(imgAddS, cv2.COLOR_BGR2RGB)) # Show imgAddS(RGB) plt.show()
Routine description 1.23:
The running results of this routine are as follows.
Shape of scalar [[150. 150. 150.]] (x,y)=10,10, img1:[ 9 9 69], imgAddV:[159 9 69], imgAddS:[159 159 219] (x,y)=20,20, img1:[ 3 252 255], imgAddV:[153 252 255], imgAddS:[153 255 255] (x,y)=30,30, img1:[ 1 255 254], imgAddV:[151 255 254], imgAddS:[151 255 255] (x,y)=40,40, img1:[ 1 255 254], imgAddV:[151 255 254], imgAddS:[151 255 255] (x,y)=50,50, img1:[ 1 255 255], imgAddV:[151 255 255], imgAddS:[151 255 255]
- Note the difference between "constant" and "scalar" when cv2.add() adds an image to a scalar:
- Adding the image to a constant value only adds the blue component of channel B to the constant, while the values of channels G and R remain unchanged, so the image is blue.
- Add the image to a scalar, "scalar" refers to a 1x3 numpy array. At this time, the B/G/R channels are added to the corresponding constants in the array, so the image is white.
- The scalar numpy array is in the form of NP. Array ([[c1,c2,c3]]), and the constants C1, C2 and C3 can be the same or different.
2. Weighted addition of image
The function cv2.addWeight() is used for weighted addition of images.
Function Description:
cv2.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]]) → dst
The function cv2.addWeighted() adds the weights of two images of the same size and type to realize the superposition and mixing of images. The calculation expression of weighted addition is:
dst = src1 * alpha + src2 * beta + gamma
Parameter Description:
- scr1, scr2: ndarray multidimensional array, representing a gray or color image
- alpha: the weight of the first image scr1, usually taken as a floating-point number between 0 and 1
- beta: the weight of the second image scr2, usually taken as a floating-point number between 0 and 1
- gamma: grayscale coefficient, offset of image correction, used to adjust brightness
- dtype the depth of the output image, that is, the number of bits of each pixel value. Optional. It is equal to src1.depth() by default
- Return value: dst, image array of weighted addition result
matters needing attention:
- When adding two pictures using the cv2.addWeight() function, the size and type (number of channels) of the pictures must be the same.
- Alpha, beta and gamma are adjustable. You can adjust the weight of the image as needed to achieve different display effects. Beta = 1-alpha and gamma = 0 are recommended.
Basic routine: 1.24 image mixing (weighted addition)
# 1.24 image blending (weighted addition) img1 = cv2.imread("../images/imgGaia.tif") # Read image imgGaia img2 = cv2.imread("../images/imgLena.tif") # Read image imgLena imgAddW1 = cv2.addWeighted(img1, 0.2, img2, 0.8, 0) # Weighted addition, a=0.2, b=0.8 imgAddW2 = cv2.addWeighted(img1, 0.5, img2, 0.5, 0) # Weighted addition, a=0.5, b=0.5 imgAddW3 = cv2.addWeighted(img1, 0.8, img2, 0.2, 0) # Weighted addition, a=0.8, b=0.2 plt.subplot(131), plt.title("1. a=0.2, b=0.8"), plt.axis('off') plt.imshow(cv2.cvtColor(imgAddW1, cv2.COLOR_BGR2RGB)) # Display img1(RGB) plt.subplot(132), plt.title("2. a=0.5, b=0.5"), plt.axis('off') plt.imshow(cv2.cvtColor(imgAddW2, cv2.COLOR_BGR2RGB)) # Show imgAddV(RGB) plt.subplot(133), plt.title("3. a=0.8, b=0.2"), plt.axis('off') plt.imshow(cv2.cvtColor(imgAddW3, cv2.COLOR_BGR2RGB)) # Show imgAddS(RGB) plt.show()
The running results of this routine are as follows:
Extension routine: 1.25 image addition of different sizes
# 1.25 image addition of different sizes imgL = cv2.imread("../images/imgB2.jpg") # Read big picture imgS = cv2.imread("../images/logoCV.png") # Read thumbnail (LOGO) x,y = 300,50 # Stacking position W1, H1 = imgL.shape[1::-1] # Large drawing size W2, H2 = imgS.shape[1::-1] # Small drawing size if (x + W2) > W1: x = W1 - W2 # Adjust the image stacking position to avoid overflow if (y + H2) > H1: y = H1 - H2 imgCrop = imgL[y:y + H2, x:x + W2] # Crop the large picture to the same size as the small picture imgS imgAdd = cv2.add(imgCrop, imgS) # cv2 addition, clipping graph and small graph superposition alpha, beta, gamma = 0.2, 0.8, 0.0 # Additive weight imgAddW = cv2.addWeighted(imgCrop, alpha, imgS, beta, gamma) # Weighted addition, clipping graph and small graph superposition imgAddM = np.array(imgL) imgAddM[y:y + H2, x:x + W2] = imgAddW # Replace the stacking position of the original imgL with the superimposed small picture cv2.imshow("imgAdd", imgAdd) cv2.imshow("imgAddW", imgAddW) cv2.imshow("imgAddM", imgAddM) cv2.waitKey(0)
It should be noted that image superposition of different sizes can be understood and processed differently. This routine is to overlay the small map to the specified position of the large map.
The running result of this routine is shown in the figure below.
Extension routine: 1.26 gradient switching of two images (changing the weight of weighted superposition)
# 1.26 gradient switching of two images (changing the weight of weighted superposition) img1 = cv2.imread("../images/imgLena.tif") # Read image imgLena img2 = cv2.imread("../images/imgB3.jpg") # Read color image (BGR) wList = np.arange(0.0, 1.0, 0.05) # start, end, step for w in wList: imgAddW = cv2.addWeighted(img1, w, img2, (1 - w), 0) cv2.imshow("imgAddWeight", imgAddW) cv2.waitKey(100)
3. Mask addition of image
Image mask, which is often written as "image mask", is to cover or mask another image with a specific image or function to control the area of image processing or the process of image processing. Image masks are often used to extract regions of interest (ROI), extract structural features, or make images with special shapes.
An image or function used for masking is called a mask, mask, template, or mask. When processing the image, the obscured area does not participate in the processing or the calculation of processing parameters; Or conversely, only the obscured areas are processed or counted.
The function cv2.add() is used for image addition operation, and the mask image can be used for masking.
cv2.add(src1, src2 [, dst[, mask[, dtype]]) → dst
The black area in the mask image (the value is 0), and the output of cv2.add is also black (the value is 0); For the non black area (non-0 value) in the mask image, the output of cv2.add is additive output. In other words, the function cv2.add performs an addition operation, does not process the black area obscured by the mask image, and remains black.
matters needing attention:
- The mask image mask is in 8-bit grayscale format, the shaded area is black (value 0), and the non shaded area is white (value 255), also known as windowed area and window.
- The shape of the mask image must be the same as that of the addition images SRC1 and src2.
Basic routine: 1.27 mask addition of image
# 1.27 image addition (mask) img1 = cv2.imread("../images/imgLena.tif") # Read color image (BGR) img2 = cv2.imread("../images/imgB3.jpg") # Read color image (BGR) Mask = np.zeros((img1.shape[0], img1.shape[1]), dtype=np.uint8) # Returns an all zero array with the same image img1 size xmin, ymin, w, h = 180, 190, 200, 200 # Position parameters of rectangular clipping region (ymin:ymin+h, xmin:xmin+w) Mask[ymin:ymin+h, xmin:xmin+w] = 255 # Mask image, ROI is white and other areas are black print(img1.shape, img2.shape, Mask.shape) imgAddMask1 = cv2.add(img1, img2, mask=Mask) # Addition with mask mask imgAddMask2 = cv2.add(img1, np.zeros(np.shape(img1), dtype=np.uint8), mask=Mask) # Extract ROI cv2.imshow("MaskImage", Mask) # Display Mask image Mask cv2.imshow("MaskAdd", imgAddMask1) # Display mask addition result imgAddMask1 cv2.imshow("MaskROI", imgAddMask2) # Displays the ROI extracted from img1 key = cv2.waitKey(0) # Wait for key command
Routine description 1.27:
The running results of this routine are as follows.
Imgaddmark1 is a standard mask addition, which saturates img1 and img2 in the window area, and other areas are shaded by black. The second image of the addition operation in imgaddmark2 is an all black image (the value is 0). The result of mask addition is to extract the masking window from the first image. The image generated by this operation is to extract the region of interest (ROI) and black masking other regions from the original image.
Extension routine: 1.28 image masks of circles and other shapes
# 1.28 addition of images (masks of circles and other shapes) img1 = cv2.imread("../images/imgLena.tif") # Read color image (BGR) img2 = cv2.imread("../images/imgB3.jpg") # Read color image (BGR) Mask1 = np.zeros((img1.shape[0], img1.shape[1]), dtype=np.uint8) # Returns an all zero array with the same image img1 size Mask2 = Mask1.copy() cv2.circle(Mask1, (285, 285), 110, (255, 255, 255), -1) # -1 indicates solid cv2.ellipse(Mask2, (285, 285), (100, 150), 0, 0, 360, 255, -1) # -1 indicates solid imgAddMask1 = cv2.add(img1, np.zeros(np.shape(img1), dtype=np.uint8), mask=Mask1) # Extract circular ROI imgAddMask2 = cv2.add(img1, np.zeros(np.shape(img1), dtype=np.uint8), mask=Mask2) # Extract ellipse ROI cv2.imshow("circularMask", Mask1) # Display Mask image Mask cv2.imshow("circularROI", imgAddMask1) # Display mask addition result imgAddMask1 cv2.imshow("ellipseROI", imgAddMask2) # Display mask addition result imgAddMask2 key = cv2.waitKey(0) # Wait for key command
The running results of this routine are as follows.
By designing image masks with circular, elliptical or other shapes, regions with different shapes can be extracted from an image.
4. Bitwise operation of image
The function cv2.bitwise provides the bit operation of the image and operates the pixel values of the image bit by bit, which is fast, efficient, convenient and flexible.
Function Description:
cv.bitwise_and(src1, src2[, dst[, mask]] → dst # Bit operation: and cv.bitwise_or(src1, src2[, dst[, mask]] → dst # Bit operation: or cv.bitwise_xor(src1, src2[, dst[, mask]] → dst # Bit operation: and or cv.bitwise_not(src1, src2[, dst[, mask]] → dst # Bit operation: non (reverse)
-
Bit operation includes four methods: bitwise and, bitwise OR, bitwise non and bitwise XOR. Its calculation method is the bitwise operation of the pixel value of the image, which has high operation efficiency and high speed.
-
Take bitwise and operation "bitwise_and" as an example:
-
- For each pixel in the image (each element in the matrix), convert the numerical value into binary;
-
- Perform bitwise operation (bitwise AND) on the values of pixels at the same position of src1 and src2: 1 & 1 = 1, 1 & 0 = 0, 0 & 0 = 0;
-
- Converts the binary result of a bit operation to decimal.
-
-
Similarly, bitwise OR, bitwise non, bitwise XOR operations convert pixel values to binary, and then convert the results back to decimal.
Parameter Description:
- scr1, scr2: image for bit operation, ndarray multidimensional array
- Mask: mask image, 8-bit grayscale format, the same size as scr1, optional parameters
- Return value: dst, bit operation result image, ndarray multidimensional array
matters needing attention:
-
- The size and type (number of channels) of images sCR1 and scr2 for bit operation must be the same.
-
- When using the mask image, the black area in the mask image (value is 0) and the output is also black (value is 0); The non black area (non-0 value) in the mask image is output by bit operation.
Basic routine: 1.29 bit operation of image
# 1.29 image bit operation img1 = cv2.imread("../images/imgLena.tif") # Read color image (BGR) img2 = cv2.imread("../images/imgB2.jpg") # Read color image (BGR) imgAnd = cv2.bitwise_and(img1, img2) # Bitwise AND imgOr = cv2.bitwise_or(img1, img2) # Bitwise OR imgNot = cv2.bitwise_not(img1) # Bitwise non (NOT) imgXor = cv2.bitwise_xor(img1, img2) # Bitwise XOR (XOR) plt.figure(figsize=(9,6)) titleList = ["img1", "img2", "and", "or", "not", "xor"] imageList = [img1, img2, imgAnd, imgOr, imgNot, imgXor] for i in range(6): plt.subplot(2,3,i+1), plt.title(titleList[i]), plt.axis('off') plt.imshow(cv2.cvtColor(imageList[i], cv2.COLOR_BGR2RGB), 'gray') plt.show()
Routine description 1.29:
The running result of this routine is shown in the figure below.
The result of bit operation of two images is shown in the figure. It seems inexplicable. It is difficult to understand the meaning of bit operation. Indeed, its bit operation is basically not used for the operation of two ordinary images. It is usually used for the mask operation of images. Let's look at the next routine.
5. Image overlay
After the two images are directly added, the color of the image will change. After the image is mixed by weighted addition, the transparency of the image will change, and the image superposition cannot be realized.
To realize image superposition, we need to comprehensively use image threshold processing, image mask, bit operation and image addition.
Taking Lena image overlay CVlogo as an example, we discuss the ideas and steps of image overlay:
- Determine the image superposition position, cut out the superposition position in the Lena image to make the superposition image the same size;
- The foreground image is binarized to generate a black-and-white mask image mask (black mask in the LOGO area) and its reverse mask image maskInv (white windowing in the LOGO area);
- Using the black-and-white mask (black covering of LOGO area) as the mask, the background image (Lena clipping image) is bit operated. The LOGO area is covered as black, and other areas remain unchanged to obtain the superimposed background image img1BG;
- Using the reverse mask maskInv (white windowing in the LOGO area) as the mask to perform bit operation on the foreground image (CVlogo), the LOGO area remains unchanged, and other areas are covered in black to obtain the superimposed foreground image img2FG;
- The background image img1BG and the foreground image img2FG obtain the superimposed image of the clipping part through cv2.add addition operation;
- Replace the superimposed position in Lena image with the superimposed image to obtain the image of Lena superimposed CVlogo.
Basic routine: 1.30 image superposition
# 1.30 image overlay img1 = cv2.imread("../images/imgLena.tif") # Read color image (BGR) img2 = cv2.imread("../images/logoCV.png") # Read CV Logo x, y = (0, 10) # Image overlay position W1, H1 = img1.shape[1::-1] W2, H2 = img2.shape[1::-1] if (x + W2) > W1: x = W1 - W2 if (y + H2) > H1: y = H1 - H2 print(W1,H1,W2,H2,x,y) imgROI = img1[y:y+W2, x:x+H2] # Crop the overlay area image from the background image img2Gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) # img2: convert to grayscale image ret, mask = cv2.threshold(img2Gray, 175, 255, cv2.THRESH_BINARY) # Convert to a binary image, generate a mask, and the LOGO area is covered with black maskInv = cv2.bitwise_not(mask) # By bit non (black-and-white transpose), an inverse mask is generated, the LOGO area is white, the window is opened, and the area outside the LOGO is black # Mask black masking area output is black, mask white windowing area and operation (the pixels in the original image remain unchanged) img1Bg = cv2.bitwise_and(imgROI, imgROI, mask=mask) # The background is generated, and the mask area of imgROI outputs black img2Fg = cv2.bitwise_and(img2, img2, mask=maskInv) # The foreground is generated, and the inverse mask area of the LOGO outputs black # img1Bg = cv2.bitwise_or(imgROI, imgROI, mask=mask) # Generate background, and cv2.bitwise_and have the same effect # img2Fg = cv2.bitwise_or(img2, img2, mask=maskInv) # Generate foreground, and cv2.bitwise_and have the same effect # img1Bg = cv2.add(imgROI, np.zeros(np.shape(img2), dtype=np.uint8), mask=mask) # Generate background, same as cv2.bitwise # img2Fg = cv2.add(img2, np.zeros(np.shape(img2), dtype=np.uint8), mask=maskInv) # Generate background, same as cv2.bitwise imgROIAdd = cv2.add(img1Bg, img2Fg) # The foreground and background are combined to obtain the superimposed image of the cropped part imgAdd = img1.copy() imgAdd[y:y+W2, x:x+H2] = imgROIAdd # The superimposed position in the background image is replaced by the superimposed image to obtain the superimposed Logo composite image plt.figure(figsize=(9,6)) titleList = ["1. imgGray", "2. imgMask", "3. MaskInv", "4. img2FG", "5. img1BG", "6. imgROIAdd"] imageList = [img2Gray, mask, maskInv, img2Fg, img1Bg, imgROIAdd] for i in range(6): plt.subplot(2,3,i+1), plt.title(titleList[i]), plt.axis('off') if (imageList[i].ndim==3): # Color image ndim=3 plt.imshow(cv2.cvtColor(imageList[i], cv2.COLOR_BGR2RGB)) # Color images need to be converted to RGB format else: # Gray image ndim=2 plt.imshow(imageList[i], 'gray') plt.show() cv2.imshow("imgAdd", imgAdd) # Display overlay image imgAdd key = cv2.waitKey(0) # Wait for key command
Routine description 1.30:
- This routine realizes the superposition of images. The intermediate process image is shown in the figure above, and the final superimposed image is shown in the figure below.
- There are many operation steps involved in image superposition. It is recommended to compare the above step description with the program and intermediate process images for reading.
- When the foreground img1Bg is generated by bit operation, the mask image mask is used to "and" imgROI and imgROI, rather than directly operate the mask and imgROI, because the mask is a gray image and imgROI is a color image, so addition or bit operation cannot be directly performed.
- When using bit operation to generate foreground and background images, imgROI and imgROI outside the mask area perform "self and operation". If the "self or operation" (see program comment statement) is used, the effect is the same. Here, you can even use the addition operation cv2.add (see program comment statement), but the operation speed of bit operation is faster.
- The function threshold() converts a grayscale image into a Binarization image with only black and white. In this method, the image is processed by fixed threshold thresh, and the gray value of pixels is set to 0 or 255.
6. Add text to the image
The function cv2.putText() is used to draw a text string on the image, that is, add text.
Function Description:
cv2.putText(img, text, pos, fontFace,fontScale,color[, thickness[, lineType[, bottomLeftOrigin]]]) → dst
The function cv2.putText() draws a text string on an image.
Parameter Description:
- img: add image of text string, ndarray multidimensional array
- Text: added text string
- pos: the coordinate of the lower left corner of the text string, such as tuple (x=100, y=100)
- Font: font type
- fontScale: font scaling factor
- Color: the color of the text string, such as tuple (255, 0, 0)
- Thickness: line thickness, in pixels
- lineType: line type
- bottomLeftOrigin: optional parameter. The default value is True, which means the data origin is in the lower left corner, and False, which means the data origin is in the upper left corner
- Return value: dst, result image, ndarray multidimensional array
matters needing attention:
- OpenCV does not support displaying Chinese characters. The text string added when using cv2.putText() cannot contain Chinese characters (including Chinese punctuation marks).
- To add Chinese characters to the image, you can use python+opencv+PIL or python+opencv+freetype. See extension routine 1.32 for details.
Basic routine: 1.31 adding text to images
# 1.31 adding text to images img1 = cv2.imread("../images/imgLena.tif") # Read color image (BGR) text = "OpenCV2021, youcans@xupt" fontList = [cv2.FONT_HERSHEY_SIMPLEX, cv2.FONT_HERSHEY_SIMPLEX, cv2.FONT_HERSHEY_PLAIN, cv2.FONT_HERSHEY_DUPLEX, cv2.FONT_HERSHEY_COMPLEX, cv2.FONT_HERSHEY_TRIPLEX, cv2.FONT_HERSHEY_COMPLEX_SMALL, cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, cv2.FONT_HERSHEY_SCRIPT_COMPLEX, cv2.FONT_ITALIC] fontScale = 1 # Font scaling color = (255, 255, 255) # Font color for i in range(10): pos = (10, 50*(i+1)) imgPutText = cv2.putText(img1, text, pos, fontList[i], fontScale, color) cv2.imshow("imgPutText", imgPutText) # Display overlay image imgAdd key = cv2.waitKey(0) # Wait for key command
Extension routine: 1.32 add Chinese text to the image
# 1.32 add Chinese text to the image imgBGR = cv2.imread("../images/imgLena.tif") # Read color image (BGR) from PIL import Image, ImageDraw, ImageFont if (isinstance(imgBGR, np.ndarray)): # Determine whether OpenCV picture type imgPIL = Image.fromarray(cv2.cvtColor(imgBGR, cv2.COLOR_BGR2RGB)) text = "OpenCV2021, Chinese font" pos = (50, 20) # (left, top), coordinates of the upper left corner of the string color = (255, 255, 255) # Font color textSize = 40 drawPIL = ImageDraw.Draw(imgPIL) fontText = ImageFont.truetype("font/simsun.ttc", textSize, encoding="utf-8") drawPIL.text(pos, text, color, font=fontText) imgPutText = cv2.cvtColor(np.asarray(imgPIL), cv2.COLOR_RGB2BGR) cv2.imshow("imgPutText", imgPutText) # Display overlay image imgAdd key = cv2.waitKey(0) # Wait for key command
[end of this section]
Copyright notice:
Welcome to pay attention "Python Xiaobai OpenCV learning class from scratch @ youcans" Original works
Original works, reprint must be marked with the original link: https://blog.csdn.net/youcans/article/details/121136047
Copyright 2021 youcans, XUPT
Crated: 2021-11-08
Welcome to pay attention "Python Xiaobai OpenCV learning class from scratch @ youcans" Series, continuously updating
Python white OpenCV learning lesson from scratch - 1. Installation and environment configuration
Python white OpenCV learning lesson from scratch - 2. Image reading and display
Python white OpenCV learning lesson from scratch - 3. Creation and modification of images
Python white OpenCV learning lesson from scratch - 4. Image superposition and mixing