草庐IT

Swift 图像处理滤镜

coder 2023-09-07 原文

我在使用我的 swift 代码中的一个过滤器时遇到问题:luminosityModifier,其他用于红色、绿色、蓝色和 alpha 的过滤器工作。如果我使用 0 作为 luminosityModifier 值,代码运行时没有错误,但如果我尝试任何其他整数,我会看到错误: 执行被中断,原因:EXC_BAD_INSTRUCTION(代码 = EXC_I386_INVOP,子代码 = 0x0)。这是此代码的最后一行。

import UIKit

let image = UIImage(named: "sample.png")!


// Process the image!
// The Filter class contains the definition of a simple RGBA variable
class Filter{
    var rgba = [UInt8](count:5, repeatedValue: 0)
}

// Here are the 5 filters that can later be selected. By modifying the RGBA values, I intened to serve the requirement to create modifiers to individual filters.
let redFilter: Filter = Filter()
redFilter.rgba[0] = 255

let greenFilter: Filter = Filter()
greenFilter.rgba[1] = 45

let blueFilter: Filter = Filter()
blueFilter.rgba[2] = 255

let alphaFilter: Filter = Filter()
alphaFilter.rgba[3] = 50

// Set luminosity Modifier in desired percentage (%), should be <100 to avoid explosion due to internal rounding
let luminosityModifier = Filter()
luminosityModifier.rgba[4] = 20



class ImageProcessor{

    var filterSequenceList: [String] = []

    //This Dictionary is later used to accept strings to set the filter the processor will apply.

    var filtersAvailable: [String: Filter] = [
        "redFilter": redFilter,
        "greenFilter": greenFilter,
        "blueFilter": blueFilter,
        "alphaFilter": alphaFilter,
        "luminosityModifier": luminosityModifier
    ]

    func addFilterToSequence(filterName: String){
        filterSequenceList.append(filterName)
    }

    func applyFilters(image: UIImage) -> UIImage{

        var filters: [Filter] = []

        // A list if filters gets populated according to the array of strings entered.
        for name in filterSequenceList{
            filters.append(filtersAvailable[name]!)
        }

        let rgbaImage = RGBAImage(image: image)!

        // Loop through each pixel
        for y in 0..<rgbaImage.height{
            for x in 0..<rgbaImage.width{
                let index = y * rgbaImage.width + x
                var pixel = rgbaImage.pixels[index]
                // Loop through each filter
                for filter in filters{
                    for value in 0...4 {

                        // RGBA values with value 0 get ignored. This means that 1 needs to be used if you wand that specific value to be very low.
                        if(filter.rgba[value] != 0 ){

                            switch value{

                            case 0:

                                pixel.red = filter.rgba[value]
                                rgbaImage.pixels[index] = pixel

                            case 1:

                                pixel.green = filter.rgba[value]
                                rgbaImage.pixels[index] = pixel

                            case 2:

                                pixel.blue = filter.rgba[value]
                                rgbaImage.pixels[index] = pixel

                            case 3:

                                pixel.alpha = filter.rgba[value]
                                rgbaImage.pixels[index] = pixel

                            case 4:

                                let red = pixel.red
                                let green = pixel.green
                                let blue = pixel.blue

                                let luminosityModifier = Double(filter.rgba[value])

                                let relativeluminosity = Double(red) * 0.2126 + Double(green) * 0.7152 + Double(blue) * 0.0722

                                let transformerRed = (relativeluminosity - Double(green) * 0.7152 - Double(blue) * 0.0722) / 0.2126

                                let transformerGreen = (relativeluminosity - Double(red) * 0.2126 - Double(blue) * 0.0722 ) / 0.7152

                                let transformerBlue = (relativeluminosity - Double(red) * 0.2126 - Double(green) * 0.7152 ) / 0.0722

                                pixel.red = UInt8(transformerRed * luminosityModifier / 100 )
                                pixel.green = UInt8(transformerGreen * luminosityModifier / 100)
                                pixel.blue =  UInt8(transformerBlue * luminosityModifier / 100)

                                rgbaImage.pixels[index] = pixel

                            default:

                                print("No image changes")

                            }
                        }
                    }
                }
            }
        }
        let newImage = rgbaImage.toUIImage()!
        return newImage
    }
}

//--------------------------------------- Start using the class here--------------------------------


var processor: ImageProcessor = ImageProcessor()

// Use the addFilterToSequence function and pass in one of the strings mentioned below. Using a non-existing filter name will cause a runtime error
// "redFilter"
// "greenFilter"
// "blueFilter"
// "alphaFilter"
// "luminosityModifier"

//processor.addFilterToSequence("redFilter")
//processor.addFilterToSequence("blueFilter")
processor.addFilterToSequence("luminosityModifier")
//processor.addFilterToSequence("greenFilter")
//processor.addFilterToSequence("alphaFilter")

processor.filterSequenceList

processor.applyFilters(image)

最佳答案

您的 rgba[4] 的索引 (4) 超出范围。只有四个元素(从零开始),第四个元素 (alpha) 位于索引 3。

至于过滤器本身,我认为您打算使用 CILuminosityBlendMode()(并删除试图完全设置其 rgba 的崩溃行)。它没有其他参数;它只是链末端的一个简单的图像输入图像输出补丁。除非你打算通过它的 alpha channel 弱地应用它(不确定这是否有效;试试看),然后只需将索引 4 更改为 3,这样你就可以在 rgba 中设置 alpha 元素数组。

关于Swift 图像处理滤镜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384909/

有关Swift 图像处理滤镜的更多相关文章

  1. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  2. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

  3. ruby-on-rails - 在 Ruby (on Rails) 中使用 imgur API 获取图像 - 2

    我正在尝试使用Ruby2.0.0和Rails4.0.0提供的API从imgur中提取图像。我已尝试按照Ruby2.0.0文档中列出的各种方式构建http请求,但均无济于事。代码如下:require'net/http'require'net/https'defimgurheaders={"Authorization"=>"Client-ID"+my_client_id}path="/3/gallery/image/#{img_id}.json"uri=URI("https://api.imgur.com"+path)request,data=Net::HTTP::Get.new(path

  4. python ffmpeg 使用 pyav 转换 一组图像 到 视频 - 2

    2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p

  5. ruby - 是否有将图像文件转换为 ASCII 艺术的命令行程序或库? - 2

    有这样的事吗?我想在Ruby程序中使用它。 最佳答案 试试这个http://csl.sublevel3.org/jp2a/此外,Imagemagick可能还有一些东西 关于ruby-是否有将图像文件转换为ASCII艺术的命令行程序或库?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/6510445/

  6. ruby-on-rails - 使用 Dragonfly 从 URL 分配图像 - 2

    我正在使用Dragonfly在Rails3.1应用程序上处理图像。我正在努力通过url将图像分配给模型。我有一个很好的表格:{:multipart=>true}do|f|%>RemovePicture?Dragonfly的文档指出:Dragonfly提供了一个直接从url分配的访问器:@album.cover_image_url='http://some.url/file.jpg'但是当我在控制台中尝试时:=>#ruby-1.9.2-p290>picture.image_url="http://i.imgur.com/QQiMz.jpg"=>"http://i.imgur.com/QQ

  7. Ruby-vips 图像处理库。有什么好的使用示例吗? - 2

    我对图像处理完全陌生。我对JPEG内部是什么以及它是如何工作一无所知。我想知道,是否可以在某处找到执行以下简单操作的ruby​​代码:打开jpeg文件。遍历每个像素并将其颜色设置为fx绿色。将结果写入另一个文件。我对如何使用ruby​​-vips库实现这一点特别感兴趣https://github.com/ender672/ruby-vips我的目标-学习如何使用ruby​​-vips执行基本的图像处理操作(Gamma校正、亮度、色调……)任何指向比“helloworld”更复杂的工作示例的链接——比如ruby​​-vips的github页面上的链接,我们将不胜感激!如果有ruby​​-

  8. ruby - Faye WebSocket,关闭处理程序被触发后重新连接到套接字 - 2

    我有一个super简单的脚本,它几乎包含了FayeWebSocketGitHub页面上用于处理关闭连接的内容:ws=Faye::WebSocket::Client.new(url,nil,:headers=>headers)ws.on:opendo|event|p[:open]#sendpingcommand#sendtestcommand#ws.send({command:'test'}.to_json)endws.on:messagedo|event|#hereistheentrypointfordatacomingfromtheserver.pJSON.parse(event.d

  9. ruby-on-rails - 如何播种图像的路径? - 2

    Organization和Image具有一对一的关系。Image有一个名为filename的列,它存储文件的路径。我在Assets管道中包含这样一个文件:app/assets/other/image.jpg。播种时如何包含此文件的路径?我已经在我的种子文件中尝试过:@organization=...@organization.image.create!(filename:File.open('app/assets/other/image.jpg'))#Ialsotried:#@organization.image.create!(filename:'app/assets/other/i

  10. ruby-on-rails - 安全地显示使用回形针 gem 上传的图像 - 2

    默认情况下:回形针gem将所有附件存储在公共(public)目录中。出于安全原因,我不想将附件存储在公共(public)目录中,所以我将它们保存在应用程序根目录的uploads目录中:classPost我没有指定url选项,因为我不希望每个图像附件都有一个url。如果指定了url:那么拥有该url的任何人都可以访问该图像。这是不安全的。在user#show页面中:我想实际显示图像。如果我使用所有回形针默认设置,那么我可以这样做,因为图像将在公共(public)目录中并且图像将具有一个url:Someimage:看来,如果我将图像附件保存在公共(public)目录之外并且不指定url(同

随机推荐