使用Opencv python从图像裁剪矩形

时间:2019-11-09 11:13:35

标签: python opencv image-processing crop

我正在尝试从屏幕截图中裁剪矩形图像,图像的背景必须为白色,而最终却变成黑色,如何更改呢?我要为最终图像制作rgb的histogtam,似乎只将垂直线绘制在零上,任何帮助都非常重要!这是我的代码:

import cv2 
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

image = cv2.imread(filename = "Screenshot from 2019-11-08 22-02-27.png")
mask = np.zeros(shape = image.shape, dtype = "uint8")
cv2.rectangle(img = mask, 
    pt1 = (0, 185), pt2 = (1900, 773), 
    color = (255, 255, 255), 
    thickness = -1)



maskedImg = cv2.bitwise_and(src1 = image, src2 = mask)
cv2.imwrite("processed.png", maskedImg)
plt.imshow(maskedImg)
plt.show()


plt.hist(maskedImg.ravel(),256,[0,256]); plt.show()


1 个答案:

答案 0 :(得分:0)

import cv2 
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

image = cv2.imread(filename = "1.png")
mask = np.zeros(shape = image.shape, dtype = "uint8")
cv2.rectangle(img = mask, 
    pt1 = (0, 185), pt2 = (1900, 773), 
    color = (255, 255, 255), 
    thickness = -1)
maskedImg = cv2.bitwise_and(src1 = image, src2 = mask)
maskedImg[np.where((maskedImg==[0,0,0]).all(axis=2))] = [255,255,255]

cv2.imwrite("processed.png", maskedImg)
plt.imshow(maskedImg)
plt.show()

将图像中存在的黑色像素转换为白色像素
原始图片 enter image description here


裁剪图像 enter image description here

enter image description here

color = ('b','g','r')
for i,col in enumerate(color):
    histr = cv2.calcHist([maskedImg],[i],None,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0,256])
plt.show()

相关问题