问题描述
我有一张照片,我想将所有白色像素更改为灰色,但仅适用于图像的特定区域.示例图片,我只想更改红色矩形外部的图片,而不更改红色矩形内部的图像:
I have a picture were I want to change all white-ish pixels to grey, but only for a certain area of the image. Example picture, I just want to change the picture outside of the red rectangle, without changing the image within the red rectangle:
我已经有了通用代码,它是其他Stackoverflow问题的一部分,该代码可以更改每个白色像素的颜色,而不仅仅是更改区域外的颜色.
I already have the general code, which was part of someone elses Stackoverflow question, that changes the colour of every white pixel instead of only just the one outside of an area.
image = cv.imread("meme 2.jpg")
hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
# Define lower and uppper limits of what we call "white-ish"
sensitivity = 19
lower_white = np.array([0, 0, 255 - sensitivity])
upper_white = np.array([255, sensitivity, 255])
# Mask image to only select white
mask = cv.inRange(hsv, lower_white, upper_white)
# Change image to grey where we found brown
image[mask > 0] = (170, 170, 170)
cv.imwrite(file, image)
推荐答案
这是在Python/OpenCV中实现此目的的一种方法.
Here is one way to do that in Python/OpenCV.
- 阅读输入内容
- 转换为HSV颜色空间
- 阈值设置所需的颜色以制作蒙版
- 使用遮罩更改图像中所有相应像素的颜色
- 为您不想更改的区域绘制一个新的矩形蒙版
- 为您要更改的区域反转新蒙版
- 将新遮罩应用于原始图像
- 将反转的新蒙版应用于颜色已更改的图像
- 将两个结果加在一起以形成最终图像
- 保存结果
输入:
import cv2
import numpy as np
# Read image
image = cv2.imread('4animals.jpg')
# Convert to HSV
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Define lower and uppper limits of what we call "white-ish"
sensitivity = 19
lower_white = np.array([0, 0, 255 - sensitivity])
upper_white = np.array([255, sensitivity, 255])
# Create mask to only select white
mask = cv2.inRange(hsv, lower_white, upper_white)
# Change image to grey where we found white
image2 = image.copy()
image2[mask > 0] = (170, 170, 170)
# Create new rectangular mask that is white on black background
x,y,w,h = 33,100,430,550
mask2 = np.zeros_like(image)
cv2.rectangle(mask2, (x,y), (x+w,y+h), (255, 255, 255), -1)
# invert mask
mask2_inv = 255 - mask2
# apply mask to image
image_masked = cv2.bitwise_and(image, mask2)
# apply inverted mask to image2
image2_masked = cv2.bitwise_and(image2, mask2_inv)
# add together
result = cv2.add(image_masked, image2_masked)
# save results
cv2.imwrite('4animals_mask.jpg', mask)
cv2.imwrite('4animals_modified.png', image2)
cv2.imwrite('4animals_mask2.jpg', mask2)
cv2.imwrite('4animals_mask2_inv.jpg', mask2_inv)
cv2.imwrite('4animals_masked.jpg', image_masked)
cv2.imwrite('4animals_modified_masked.jpg', image2_masked)
cv2.imwrite('4animals_result.jpg', result)
cv2.imshow('mask', mask)
cv2.imshow('image2', image2)
cv2.imshow('mask2', mask2 )
cv2.imshow('mask2_inv', mask2_inv)
cv2.imshow('image_masked', image_masked)
cv2.imshow('image2_masked', image2_masked)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
颜色遮罩:
矩形蒙版:
倒置的矩形蒙版:
更改颜色的图像:
已屏蔽的输入:
蒙版颜色更改的图像:
结果:
这篇关于在python中使用opencv更改图像中区域的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!