Unknown C++ exception from OpenCV code

Symptom

When I ran my OpenCV code and the following exception was raised.

Unknown C++ exception from OpenCV code
File …, line …, in … keyboard = cv2.waitKey(1) & 0xFF

Unknown C++ exception from OpenCV code
File File …, line …, in …cv2.imshow(‘frame’, frame)

Version

macOS Monterey 12.3.1
python: 3.9.12
OpenCV: 4.5.5
opencv-python: opencv_python-4.5.5.64-cp37-abi3-macosx_11_0_arm64

Cause

The code was not invoked in the main thread. Moving the code to the main thread and then it worked. So, I’m assuming that OpenCV on macOS shall run on the main thread.
Please note that the code worked perfectly on Windows 10. So, it is only on macOS.

Solution

On macOS, run OpenCV code in the main thread.

[{‘code’: 324, ‘message’: ‘Not valid video’}]

Symptom

I created a twitter bot with ffmpeg-python. When I uploaded a video created by ffmpeg-python to twitter, it returned [{‘code’: 324, ‘message’: ‘Not valid video’}] error.

Cause

The video was encoded by mp4, which is obsolete for twitter.

Solution

Use the h264 codec for twitter.

ffmpeg.output(video, video_out, vcodec=’h264′)

FileNotFoundError: [Errno 2] No such file or directory: ‘ffmpeg’ when called by launchd

Sympton

FileNotFoundError: [Errno 2] No such file or directory: ‘ffmpeg’ when called by launchd.

It works as expected when called from shell.

Cause

PATH for /usr/local/bin/ffmpeg is missing.

sys.version: (‘3.10.0 (v3.10.0:b494f5935c, Oct 4 2021, 14:59:20) [Clang 12.0.5 ‘
‘(clang-1205.0.22.11)]’)
shutil.which(“python3”): ‘/usr/bin/python3’
os.getenv(“PATH”): ‘/usr/bin:/bin:/usr/sbin:/sbin’
os.getenv(“PYTHONPATH”): None

Solution

Explicitly specify the PATH environment variable in the plist.

shutil.which(“python3”): ‘/usr/local/bin/python3’
os.getenv(“PATH”): ‘/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin’
os.getenv(“PYTHONPATH”): None

Note:

launchctl unload and load is required to update the PATH.
PYTHONPATH is not required.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>test_launchd.test</string>

        <key>EnvironmentVariables</key>
        <dict>
                <key>PATH</key>
                <string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
        </dict>

        <key>ProgramArguments</key>
        <array>
                <string>/usr/local/bin/python3</string>
                <string>/users/uchukamen/Desktop/Python/test_launchd/test.py</string>
        </array>

ML Image Classifier not giving expected results on simulators

Symptom

I created an Image Classifier app, “Chichibu Unkai Watcher”, and it returns right results on a real iPhone device. Also it returns right results on mac catalyst. But, I found that the iPhone/iPad simulators do not return expected results.

XCode Version 13.1 (13A1030d)
Simulator Version 13.1 (970)
Create ML Version 3.0 (78.6)

Fig.1 iPhone real device: Unkai confidence level is ~0%.
Fig.2 mac app on macOS Catalyst: Unkai confidence level is ~0%.
Fig.3 iPhone Simulator: Unkai confidence level is 69%
All of those are using a same image data, and the Unkai confidence level should be ~0%.

Discussion

I tried some GPU settings on the simulator app, also some compiler settings changes, but it does not resolve this symptom. I found an article on the Stack Overflow which says it might be caused by the simulator. At this moment, I’m assuming this is caused by the simulator.

Reference

https://stackoverflow.com/questions/65642606/action-ml-classifier-not-giving-expected-results/69974393#69974393

Per Sheldon, he is suggesting to run one on a real device.

Fig.1 iPhone real device

Fig.2 mac Catalyst app run on a real mac

Fig.3 iPhone Simulator

Error: unrecognized selector sent to instance

Error

2021-07-17 17:22:01.168937+0900 MaskedBlur2[19987:9237645] -[NSConcreteValue X]: unrecognized selector sent to instance 0x2835e0690

2021-07-17 17:22:01.172931+0900 MaskedBlur2[19987:9237645] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[NSConcreteValue X]: unrecognized selector sent to instance 0x2835e0690’

*** First throw call stack:

(…)

libc++abi: terminating with uncaught exception of type NSException

*** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[NSConcreteValue X]: unrecognized selector sent to instance 0x2835e0690’

terminating with uncaught exception of type NSException


Cause

Unexpected data type was passed for a parameter.
In this case, forKey:kCIInputCenterKey is expecting CIVector, but CGPoint was passed.

OK

    var location: CIVector= CIVector(cgPoint: CGPoint(x: 0, y: 0))

    radialMask.setValue(imageCenter, forKey:kCIInputCenterKey)

Error

    var location: CGPoint= CGPoint(x: 0, y: 0)

    radialMask.setValue(location, forKey:kCIInputCenterKey)

SwiftUI: ForEach, forEach, for in の違い

SwiftUIでは、ForEach, forEach, for in の動きが異なります。

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            // OK
            // SwiftUI の ForEach は View を返すので OK
            ForEach(1..<5) { i in Text("hello") }
            
            // Error: Closure containing control flow statement cannot be used with result builder 'ViewBuilder'
            // クロージャーを持つ制御文は 複数のView を構成する ViewBuilder として使えない
            // 要は、次のように複数の Text からなる View を構成することができない
            for i in 1..<5 { Text("hello") }
            
            // Error: Type '()' cannot conform to 'View'
            // forEach は View を返さない
            [1,2,3,4].forEach{ d in Text("hello") }
        }
    }
}

XCode UnitTest Error : Multiple commands produce …

Symptom

  1. Create a project.
  2. Add a new target with Swifter by pod install
  3. run a unit test, then Multiple commands produce … error comes up.

Cause

Error Message is as follows.

Multiple commands produce …..
1) Target ‘appname’ has … /appname.app’
2) Target ‘appname_Twitter (iOS)’ has…./appname.app’

It means, there are two files with appname.app for two different targets.

Solution

Rename one of the product name, and clean rebuild.
In my case, I renamed my app with Swifter from TARGETS >> Build Settings “Product Name” from appname to appname2.

Warning: To use these entitlements, add them to your entitlements file. Otherwise, remove unused entitlements from your provisioning profile.

Symptom

When I was building an App Clip, the following warning was reported by XCode. Provisioning profile “iOS Team Provisioning Profile: com.aiharasoft.***App” for “***” contains entitlements that aren’t in the entitlements file: com.apple.developer.associated-appclip-app-identifiers. To use these entitlements, add them to your entitlements file. Otherwise, remove unused entitlements from your provisioning profile.

Solution

From https://developer.apple.com/, “Certificates, Identifiers & Profiles” >> “Profiles” >> Choose profile. Somehow, the Status got into Invalid.

And I edited the profile and saved, and the status turned to Active.Rebuild XCode and the warning has gone.

Another point is when I added “Associated Domains” from capabilities, only on debug was selected. Thus, two entitlements file for debug and release were created. I did not notice the two entitlements, debug and release files became inconsistent, and then uploaded to App Store Connect. So, the app got into into inconsistent state.

I’m not sure, but as the warning says, inconsistency between Provisioning Profile and *App.entitlements causes this warning.

Anyway, check the Profiles, entitlements, and the consistencies, first.

  1. https://developer.apple.com/, “Certificates, Identifiers & Profiles”
  2. App.entitlements in Xcode file.

XCode cannot get into debug mode with message: “Finished running”

Symptom

When I started debugging with XCode on a physical iPhone 8 device, the debugger stopped with “Finished running”. The app was successfully deployed, up and running on a device, but it could not start debugging.

On a simulator, Xcode could get into debug mode.

Restarting xcode did not solve the problem.

Solution

Reboot the iPhone and restart Xcode.

[Error] The file couldn’t be opened because you don’t have permission to view it.

Symtom

While accessing PHPicker, the following error occurred. However, I could access the image successfully.

2021-03-07 16:28:16.910394+0900 **** [4516:1164237] [default] [ERROR] Could not create a bookmark: NSError: Cocoa 257 “The file couldn’t be opened because you don’t have permission to view it.” }

Solution

Reference:

https://developer.apple.com/forums/thread/654021

https://developer.apple.com/forums/thread/652695

Per Apple Frameworks Developer, they are aware of this issue (64630315) and it will be fixed in a future release. (as of 2020 Summer).

To workaround the permission error for now, you need to reset your simulator / device.