使用Opencv python从图像中裁剪矩形

问题描述 投票:1回答:1

我正在尝试从屏幕截图中裁剪矩形图像,图像的背景必须为白色,而最终却变成黑色,如何更改?我要为最终图像制作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()


python opencv image-processing crop
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.