Jerry's Blog

Recording what I learned everyday

View on GitHub


7 February 2020

OpenCV(2) -- shapes, Image Operations, Bitwise Operation

by Jerry Zhang

Drawing shapes

import numpy as np
import cv2 as cv

# img = cv.imread('lena.jpg', 1)
img = np.zeros([512, 512, 3], np.uint8)

img = cv.line(img, (0, 0), (255, 255), (0, 0, 255), 5)
img = cv.arrowedLine(img, (0, 255), (255, 255), (255, 0, 0), 10)

img = cv.rectangle(img, (384, 0), (510, 128), (0, 0, 255), 5)  # 最后一个参数用-1表示填充整个图形
img = cv.circle(img, (447, 63), 63, (0, 255, 0), -1)
font = cv.FONT_HERSHEY_COMPLEX
img = cv.putText(img, 'OpenCV', (10, 500), font, 4, (0, 255, 255), 10, cv.LINE_AA)

cv.imshow('image', img)
cv.waitKey(0)
cv.destroyAllWindows()

Image Operations

检查图片的长宽,大小,数据类型;拆分通道;把一个部分复制到另一个位置;重新规定尺寸;把两个图片重合到一起

import cv2 as cv

img = cv.imread('messi5.jpg')
img2 = cv.imread('opencv-logo.png')

print(img.shape)
print(img.size)
print(img.dtype)
b, g, r = cv.split(img)
img = cv.merge((b, g, r))

ball = img[280:340, 330:390]
img[273:333, 100:160] = ball

img = cv.resize(img, (512, 512))
img2 = cv.resize(img2, (512, 512))

# dst = cv.add(img, img2)

dst = cv.addWeighted(img, .9, img2, .1, 0)


cv.imshow('image', dst)
cv.waitKey(0)
cv.destroyAllWindows()

Bitwise Operation

import cv2 as cv
import numpy as np

# img_1 = np.zeros((250, 500, 3), np.uint8)
# cv.rectangle(img_1, (250, 0), (500, 250), (255, 255, 255), -1)
# cv.imwrite('image_1.png', img_1)

img1 = np.zeros((250, 500, 3), np.uint8)
img1 = cv.rectangle(img1, (200, 0), (300, 100), (255, 255, 255), -1)
img2 = cv.imread('image_1.png')

# bitAnd = cv.bitwise_and(img2, img1)
bitOr = cv.bitwise_or(img2, img1)

cv.imshow('img1', img1)
cv.imshow('img2', img2)
cv.imshow('bitAnd', bitOr)

cv.waitKey(0)
cv.destroyAllWindows()
tags: OpenCV