简体   繁体   English

如何使用Matlab将辣椒图像中的绿色像素更改为金色?

[英]How to change green pixels to gold color in peppers image with matlab?

I want to change green color pixels to gold color in peppers.png image in Matlab. 我想在Matlab中的peppers.png图像中将green像素更改为gold How can I do this task? 我该怎么做? Thanks very much for your help 非常感谢您的帮助

Introduction 介绍

Using the HSV colorspace gives a better intuition of detecting a certain color hue and manipulating it. 使用HSV色彩空间可以更好地直观地检测出某种色彩并对其进行处理。 For further information, read the following answer . 有关更多信息,请阅读以下答案

Solution

Given an image in hsv format, each color has a certain range which it can reside in. In the peppers image, the hue channel of green peppers is in the range [40/360,180/360] (more or less). 给定hsv格式的图像,每种颜色都有一个可以驻留的范围。在Peppers图像中,青椒的色相通道在[40 / 360,180 / 360]范围内(或多或少)。 Also, the color gold can be identified by a hue value of 0.125 and 'V' value of 0.8. 同样,可以通过0.125的色相值和0.8的“ V”值识别金色。 Therefore, a good way to change green to gold in a certain picture will be as follows: 因此,在特定情况下将绿色变为金色的好方法如下:

  1. transform the image to hsv. 将图像转换为hsv。
  2. locate green colors by identifying hue value between the range [40/360,180/360]. 通过识别[40 / 360,180 / 360]范围内的色相值来定位绿色。
  3. changing their first channel to 0.125, and their second channel to 0.8. 将其第一通道更改为0.125,将其第二通道更改为0.8。
  4. transform back to rgb. 转换回rgb。

*comment: instead of fully changing the third channel of the green pixels to 0.8, it will be better to perform an averaging of 0.8 with the originally stored value, to get a more natural effect (see code below). *注释:与其将绿色像素的第三个通道完全更改为0.8,不如对原始存储的值进行平均0.8更好,以获得更自然的效果(请参见下面的代码)。

Code

%reads the image. converts it to hsv.
I = imread('peppers.png');
hsv = rgb2hsv(I);

%locate pixels with green color
GREEN_RANGE = [40,180]/360;
greenAreasMask = hsv(:,:,1)>GREEN_RANGE(1) & hsv(:,:,1) < GREEN_RANGE(2);

%change their hue value to 0.125
HUE_FOR_GOLD = 0.12;
V_FOR_GOLD = 0.8;
goldHsv1 = hsv(:,:,1);
goldHsv1(greenAreasMask)=HUE_FOR_GOLD;
goldHsv3 = hsv(:,:,3);
goldHsv3(greenAreasMask)=V_FOR_GOLD;
newHsv = hsv;
newHsv(:,:,1) = goldHsv1;
newHsv(:,:,3) = newHsv(:,:,3) + goldHsv3 / 2;
%transform back to RGB
res = hsv2rgb(newHsv);

Result 结果

As you can see, the green pixels became more goldish. 如您所见,绿色像素变得更加金色。 There is a room for improvement, but I think that this would be a good start for you. 有改进的余地,但是我认为这对您来说是个好的开始。 To improve the result you can modify the green and gold HSV values, and use morphological operations on greenAreasMask. 为了改善结果,您可以修改绿色和金色HSV值,并在greenAreasMask上使用形态学运算。 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM