我们一直在尝试修复这个程序几个小时,但似乎没有任何工作,我们只是无法弄清楚问题是什么。除了红色像素之外,它应该使整个图片为黑白。(https://imgur.com/a/gxRm3N1之后应该是这样)
这是使用该程序后的结果,整个图片变红了:
https://imgur.com/a/yWYVoIx我怎样才能解决这个问题?
from image_helper import *
img = load_rgb_image("ara.jpg")
w, h = img.size
pixels = load_rgb_pixels("ara.jpg")
#img.show()
for i in range(w*h):
r,g,b = pixels[i]
new_r = 2*r
new_g = g // 2
new_b = b + 10
pixels[i] = (new_r, new_g, new_b)
new_img = new_rgb_image(w, h, pixels)
new_img.show()
在 MATLAB 中实现了一个excellent solution。
我很想把代码从 MATLAB 翻译成 Python(使用 OpenCV)。
将图像转换为HSV color space。
选择“非红色”像素。在 HSV 颜色空间中,第一个通道是色调-对于被认为是红色的像素,有一系列色调。
将所选像素饱和度通道设置为 0。(饱和度为零的像素为灰色)。
将图像从 HSV 转换回 BGR 颜色空间。
这是 Python 代码(原始 MATLAB 代码的对话):
import cv2
# The following code is a Python conversion to the following MATLAB code:
# Original MATLAB code: https://stackoverflow.com/questions/4063965/how-can-i-convert-an-rgb-image-to-grayscale-but-keep-one-color
img = cv2.imread('roses.jpg') # Load image.
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Convert the image to HSV color space.
h = hsv[:, :, 0] # Note: in OpenCV hue range is [0,179]) The original MATLAB code is 360.*hsvImage(:, :, 1), when hue range is [0, 1].
s = hsv[:, :, 1] # Get the saturation plane.
non_red_idx = (h > 20//2) & (h < 340//2) # Select "non-red" pixels (divide the original MATLAB values by 2 due to the range differences).
s[non_red_idx] = 0 # Set the selected pixel saturations to 0.
hsv[:, :, 1] = s # Update the saturation plane.
new_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) # Convert the image back to BGR space
# Show images for testing:
cv2.imshow('img', img)
cv2.imshow('new_img', new_img)
cv2.waitKey()
cv2.destroyAllWindows()
cv2.imwrite('new_img.jpg', new_img)
笔记:
有关用于选择颜色范围的方法,请参阅original post。
参考文章有一个更简单的解决方案,使用简单的 for 循环(具有较差的结果),更类似于您的代码。
考虑使用此代码作为参考。
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(6条)