readJPEG()我使用包中的彩色 jpg 图像进行读取jpeg。现在我在 R 中将图像作为三维数组(宽度、高度、通道)。
我想将这些图像数组转换为 HSL 或 HSV 颜色空间,对图像进行变异,然后再次将它们保存为 RGB 格式的 JPG。然而,由于图像非常大(5000 x 8000),循环遍历每个单元格会非常耗时。我找到了可以快速将图像转换为 HSV 颜色空间的软件包OpenImageR,但是,我对“饱和度”通道中的大负值感到困惑。此外,该包不包含将图像转换回来的功能。
是否有任何软件包可以执行从 RGB 到 HSL 或 HSV(以及反向)的快速转换?或者有没有其他方法可以快速进行转换?
这些是我目前尝试按元素转换为一个方向的尝试:
# load packages
library(jpeg)
library(plotwidgets)
# load image
img <- readJPEG(img_path)
img <- img * 255
# new empty image
img_new <- array(NA, dim = dim(img))
# this takes way too long
for (img_row in 1:dim(img)[1]) {
for (img_col in 1:dim(img)[2]) {
img_new[img_row,img_col,] <- round(rgb2hsl(as.matrix(img[img_row,img_col,])))
}
}
# this takes also way too long
for (img_row in 1:dim(img)[1]) {
img_new[img_row,,] <- t(round(rgb2hsl(t(matrix(img[img_row,,], ncol = 3)))))
}
# this takes also ages
rgb_hsl_fun <- function(x) {
as.numeric(rgb2hsl(matrix(x)))
}
img_hsl <- apply(X = img, MARGIN = c(1,2), FUN = rgb_hsl_fun)
Run Code Online (Sandbox Code Playgroud)
整个事情做起来非常简单。colorspace为此使用库。
这是代码。
library(jpeg)
library(colorspace)
#Reading a jpg file
img = readJPEG("img.jpg") * 255
#Row-by-row conversion
for(i in 1:dim(img)[1]){
#Convert to HSV format
hsv = RGB(img[i,,1], img[i,,2], img[i,,3]) |> as("HSV")
#Mutation of H, S, V components
attributes(hsv)$coords[,"H"] = attributes(hsv)$coords[,"H"]/2
attributes(hsv)$coords[,"S"] = attributes(hsv)$coords[,"S"]*.998
attributes(hsv)$coords[,"V"] = attributes(hsv)$coords[,"V"]-1
#Convert to RGB format and save to the current line.
rgb = as(hsv, "RGB")
img[i,,1] = attributes(rgb)$coords[,"R"]
img[i,,2] = attributes(rgb)$coords[,"G"]
img[i,,3] = attributes(rgb)$coords[,"B"]
}
#Save to JPG file
writeJPEG(img / 255, "img_hsv.jpg")
Run Code Online (Sandbox Code Playgroud)
请注意,要获取各个 H、S、V(或 R、G、B)分量,您必须使用该coords属性。
正如你所看到的,我对组件H、S、V的突变如下:
但是,如果您更喜欢在 HLS 调色板上进行突变,这是可能的。
#Reading a jpg file
img = readJPEG("img.jpg") * 255
#Row-by-row conversion
for(i in 1:dim(img)[1]){
#Convert to HLS format
hls = RGB(img[i,,1], img[i,,2], img[i,,3]) |> as("HLS")
#Mutation of H, S, V components
attributes(hls)$coords[,"H"] = attributes(hls)$coords[,"H"]/2
attributes(hls)$coords[,"L"] = attributes(hls)$coords[,"L"]/2
attributes(hls)$coords[,"S"] = attributes(hls)$coords[,"S"]/2
#Convert to RGB format and save to the current line.
rgb = as(hls, "RGB")
img[i,,1] = attributes(rgb)$coords[,"R"]
img[i,,2] = attributes(rgb)$coords[,"G"]
img[i,,3] = attributes(rgb)$coords[,"B"]
}
#Save to JPG file
writeJPEG(img / 255, "img_hls.jpg")
Run Code Online (Sandbox Code Playgroud)
希望这就是您正在寻找的。