python 图像去掉指定颜色,我想使用python将图像中的颜色从特定颜色范围更改为另一种颜色...

4KUoI.png

I want to change the brown areas to RED (or another color).

Just I don't know how to get the ranges for brown and put them in python code.

I know how to change a single color, but not a range of colors.

Any Ideas?

Thanks

解决方案

This should give you an idea - it is pretty well commented:

#!/usr/local/bin/python3

import cv2 as cv

import numpy as np

# Load the aerial image and convert to HSV colourspace

image = cv.imread("aerial.png")

hsv=cv.cvtColor(image,cv.COLOR_BGR2HSV)

# Define lower and uppper limits of what we call "brown"

brown_lo=np.array([10,0,0])

brown_hi=np.array([20,255,255])

# Mask image to only select browns

mask=cv.inRange(hsv,brown_lo,brown_hi)

# Change image to red where we found brown

image[mask>0]=(0,0,255)

cv.imwrite("result.png",image)

eOLEY.png

How did I determine the limits for "brown"? I located a brown area in the image, and cropped it out to remove everything else. Then I resized it to 1x1 to average all the shades of brown in that area and converted it to HSV colourspace, I printed that and took the value for Hue which was 15 and went +/-5 to give a range of 10-20. Increase the range to 8-22 to select a wider range of hues.

HSV/HSL colourspace is described on Wikipedia here.

Keywords: Image processing, Python, OpenCV, inRange, range of colours, prime.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Python的OpenCV库来实现将图像指定颜色换成新颜色的功能。具体实现步骤如下: 1. 导入必要的库:cv2和numpy。 ```python import cv2 import numpy as np ``` 2. 读取图像使用cv2.imread()函数读取需要进行颜色替换的原始图像。 ```python img = cv2.imread('image.jpg') ``` 3. 定义需要替换的颜色范围使用cv2.inRange()函数定义需要替换的颜色范围。该函数返回一个二值化图像,其指定颜色的像素值被设置为255,其他像素值被设置为0。 ```python lower_range = np.array([0, 0, 0]) # 指定颜色的下限范围 upper_range = np.array([50, 50, 50]) # 指定颜色的上限范围 mask = cv2.inRange(img, lower_range, upper_range) # 定义颜色范围 ``` 4. 替换指定颜色使用cv2.bitwise_and()函数将原始图像指定颜色部分替换为新颜色。 ```python new_color = (255, 0, 0) # 新颜色 res = cv2.bitwise_and(img, img, mask=mask) res[mask == 255] = new_color ``` 5. 显示结果:使用cv2.imshow()函数显示处理后的图像,并使用cv2.waitKey()函数等待用户按下任意键关闭窗口。 ```python cv2.imshow('Result', res) cv2.waitKey(0) cv2.destroyAllWindows() ``` 完整代码如下: ```python import cv2 import numpy as np img = cv2.imread('image.jpg') lower_range = np.array([0, 0, 0]) upper_range = np.array([50, 50, 50]) mask = cv2.inRange(img, lower_range, upper_range) new_color = (255, 0, 0) res = cv2.bitwise_and(img, img, mask=mask) res[mask == 255] = new_color cv2.imshow('Result', res) cv2.waitKey(0) cv2.destroyAllWindows() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值